Spring Boot + SPRING REST + Swagger + JPA +内存H2 DB

时间:2018-07-09 06:44:19

标签: java spring spring-boot spring-data-jpa spring-rest

我正在使用Spring Boot进行Spring REST。我开始将值硬编码为 DAOService ,如下所示,一切正常

@Component
public class UserDAOService {

    static List<User> users = new ArrayList<>();
    static int userCount = 3;

    static {
        users.add(new User("adam", new Date(), 1));
        users.add(new User("eve", new Date(), 2));
        users.add(new User("joe", new Date(), 3));
    }

    public User saveUser(User user) {
        if (user.getId() == null) {
            user.setId(++userCount);
        }
        users.add(user);
        return user;
    }

    public List<User> findAll() {
        System.out.println("finding all users");
        return users;
    }

    public User findOne(int id) {

        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

但是后来我试图集成JPA并将bean转换为实体,如下所示,起初我在创建名为'documentationpluginsbootstrapper'的bean时出错,但是通过从SwaggerConfig类中删除@Configuration注释解决了。异常 创建名称为'repositorySearchController' 的bean时出错。.日志显示在末尾

    @ApiModel(description="all details about user")
    @Entity
    public class User {

        @Id
        @GeneratedValue
        private Integer id ;

        @Size(min=2,max=12,message="username should be atleast 2 characters")
        private String name;
        @Past
        private Date birthDate; 

        public User(String name, Date birthDate, Integer id) {
            super();
            this.name = name;
            this.birthDate = birthDate;
            this.id = id;
        }
        public User() {
            // TODO Auto-generated constructor stub
        } 
//setters and getters    
    }

日志:

org.springframework.beans.factory.UnsatisfiedDependencyException :在...... spring- data-rest-webmvc-3.0.8.RELEASE.jar

需要输入来解决此问题。

1 个答案:

答案 0 :(得分:0)

要连接到 H2数据库,您应将以下属性添加到application.properties文件中:

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.platform=h2
spring.datasource.initialize=true
spring.datasource.continue-on-error=true

,您可以从以下网址访问BD:http://localhost:8080/h2-console/