我有一个带有 MySQL 的 Spring Boot Application + JPA。在我的 Controller 中,当我发布一个实体时,我可以调用 repository.save,并返回“创建/更新”对象。
但是,当我查看数据库时,我发现该对象没有更新。
这是我的 application.yml:
spring:
jpa:
show-sql: true
generate-ddl: false
hibernate:
ddl-auto: none
properties:
hibernate.dialect: org.hibernate.dialect.MySQLDialect
org.hibernate.envers.store_data_at_delete: true
org.hibernate.envers.global_with_modified_flag: true
org.hibernate.envers.track_entities_changed_in_revision: true
datasource:
initialize: false
url: jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:databaseName}?createDatabaseIfNotExist=true
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:root}
driver-class-name: com.mysql.jdbc.Driver
hikari:
minimumIdle: 20
maximumPoolSize: 30
idleTimeout: 5000
data-source-properties:
cachePrepStmts: true
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
你知道我还需要做什么吗?
这是我的 Controller :
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public MyEntity saveMyEntity(@Valid @RequestBody final MyEntity myEntity) {
Assert.notNull(myEntity, "The entry cannot be null");
return myEntityService.save(myEntity);
}
和 MyEntityService:
@Override
@UserCanCud
public Entity save(final Entity entity) {
Assert.notNull(entity);
final Entity savedEntity = repository.save(entity);
return savedEntity;
}
最佳答案
在我(有限的)经验中,由于 Spring 在幕后发生的魔法,这些类型的问题有点难以调试,但我会尝试提供一些建议来帮助我解决类似的问题 - 希望这能给你轻推你需要的。@Transactional
表示法建立了一个事务范围,该范围规定事务何时开始和结束,也称为其边界。如果您在此边界之外操作,您将收到错误或无法按预期工作。
首先,我发现这个文档对 Spring 事务最有帮助:http://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html特别this section
其次,您可能希望启用跟踪级别日志和潜在的 SQL 语句来帮助调试。为此,我在 application.properties
中添加了以下内容- 您可以将相同的内容添加到您的 application.yml
中有一些小的调整
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.show-sql=true
logging.level.org.hibernate=TRACE
这里会有很多输出,但你会对幕后发生的事情有一个很好的了解。
第三,也是我学习使用最重要的部分
@Transactional
是对 DAO 的每次调用都会创建一个新 session - 或者 - 如果在同一事务范围内,则重用现有 session 。有关这方面的示例,请参阅上面的文档。现在,我怀疑当您读回更新后的对象时,您的事务仍被认为是打开的。尝试做一个
flush
在您的保存方法中,看看这是否有助于将您的更改保存回数据库。希望您能够使用上面的资源在不进行过多搜索的情况下找到问题,如果没有,您至少应该有一些关于为什么持久性不持久的更完整的信息。
关于hibernate - 当repository.save时Spring Boot + JPA + Hibernate不提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966901/