【发布时间】:2020-03-26 12:27:08
【问题描述】:
我想知道如何使用 hibernate 将 h2 数据库中的数据库对象读取到我的 spring 控制器中(或者其他任何东西,我并没有与 hibernate 结婚)。
我有一个使用 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 控制台看到我的表存在其中的数据。我也做了一个实体对象。
但是我不知道如何将我的实体对象从 h2 读取到我的控制器中。有人可以指出正确的资源或解释如何去做吗?
【问题讨论】:
-
您可以使用来自 spring-boot-starter-data-jpa 的 CrudRepository 读取实体对象。见这里spring.io/guides/gs/accessing-data-jpa
-
@Devilluminati 它并没有完全解释我将如何在控制器中使用它。我最大的问题是能够在控制器中获取对象,以便将其传递给生成的网页。
-
这样操作dzone.com/articles/spring-boot-with-spring-data-jpa。使用实体对象作为第一个通用类型创建存储库。二是ID长。将此存储库注入您的控制器并执行您想做的任何事情。在 MVC 中,您可以将数据放在地图中以在模板中读取它,例如百里香叶。如果这不能回答问题,我不明白你到底在寻找什么。
标签: spring hibernate spring-boot spring-data-jpa h2