我正在设置一个准系统Spring Boot项目described here,而且我遇到了基本设置的问题。
似乎没有调用DatabaseLoader,当我打开这个项目的H2控制台时,我看不到包含Employee表的模式。
这是我的pom.xml的相关部分:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<!--
<scope>runtime</scope>
-->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
我的域名:
@Data
@Entity
public class Employee {
private @Id @GeneratedValue Long id;
private String firstName;
private String lastName;
private String description;
public Employee() {}
public Employee(String firstName, String lastName, String description) {
this.firstName = firstName;
this.lastName = lastName;
this.description = description;
}
}
数据库加载器: 公共类DatabaseLoader实现CommandLineRunner { 私人最终EmployeeRepository存储库;
@Autowired
public DatabaseLoader(EmployeeRepository repository) {
this.repository = repository;
}
@Override
public void run(String... strings) throws Exception {
this.repository.save(new Employee("duke", "earl", "dude"));
}
}
在localhost:8080 / console启动应用程序后导航到控制台,只显示了一个INFORMATION_SCHEMA和users菜单的jdbc:h2:〜/ test。我还将其设置为CRUD存储库,虽然我可以发布到它,但似乎没有保存任何属性数据,但是可以识别Employees资源。
POST:{"firstName": "Bilbo", "lastName": "Baggxins", "description": "burglar"}
回来:
{
"_links": {
"self": {
"href": "http://localhost:8080/api/employees/4"
},
"employee": {
"href": "http://localhost:8080/api/employees/4"
}
}
}
答案 0 :(得分:8)
Spring Boot的默认h2网址为:$("#third").click(function(){
要使用jdbc:h2:mem:testdb
,您必须将其添加到jdbc:h2:~/test
:
application.properties
发生了什么,你是在spring-boot的内存数据库(testdb)中编写Employee。然后,打开h2-console到spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:~/test
,它会动态创建它,让你浏览空虚。
使用jdbc:h2:~/test
,您可以打开浏览器spring.h2.console.enabled=true
并查看数据库内容。使用以下设置:
答案 1 :(得分:0)
这是从Josh Long无耻地借来的。这是一个有效的CommandLineRunner
实现。 Github full code
@Component
class SampleRecordsCLR implements CommandLineRunner {
private final ReservationRepository reservationRepository;
@Autowired
public SampleRecordsCLR(ReservationRepository reservationRepository) {
this.reservationRepository = reservationRepository;
}
@Override
public void run(String... args) throws Exception {
Stream.of("Josh", "Jungryeol", "Nosung", "Hyobeom",
"Soeun", "Seunghue", "Peter", "Jooyong")
.forEach(name -> reservationRepository.save(new Reservation(name)));
reservationRepository.findAll().forEach(System.out::println);
}
}