使用 spring boot 和 h2 读取数据库对象

Read database object with spring boot and h2

我想知道如何使用 hibernate(或其他任何东西,我没有嫁给 hibernate)将 h2 数据库中的数据库对象读入我的 spring 控制器。

我有一个使用 gradle 的简单项目设置。

我的application.properties

spring.thymeleaf.cache=false
# Datasource
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:database
spring.datasource.username=something
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
# Hibernate
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

我可以看到 schema.sql 和 data.sql 正在执行。我使用 h2 控制台看到我的 table 存在,其中包含数据。我也做了一个实体对象。

但是我不知道如何从 h2 读取我的实体对象并读入我的控制器。有人可以指出正确的资源或解释如何去做吗?

到目前为止,最简单的方法是使用 spring-data-jpa。为此,您需要一个实体(即带有 @javax.persistence.Entity 注释的 class)来表示 table.

中的一行
@Entity
public class Thing {
    @Id
    private String id;
    private String name;
}

然后你需要一个可以从数据库读取和写入的存储库。这是一个扩展 spring 存储库 classes 之一的接口,通常是 CrudRepository,像这样:

public interface CustomerRepository extends CrudRepository<Thing, String> {
  Thing findById(long id);
}

然后,将存储库自动连接到控制器的构造函数中,您就快完成了。最后一部分是调用 repo 上的方法之一。您不必实际实施 repo,spring 会为您完成。基本存储库有很多有用的默认方法,您甚至不必在代码中列出这些方法。在 spring 的网站上有很多关于所有这些的参考资料,我已经将你链接到一个很好的教程(它有 gradle 示例,但你真的应该使用 maven,因为它是各方面都好多了)。