【发布时间】:2019-05-30 03:00:12
【问题描述】:
我想知道通过 Spring Data 从 DTO 转换到数据库的最佳做法是什么?
这是我迄今为止尝试过的:
@Transactional
public void saveTemplatesFromDTOList(List<TemplateDTO> templateDTOList) {
for (TemplateDTO templateDTO : templateDTOList) {
em.merge(templateDTO);
}
}
但是,这不起作用。我用 Spring Data 存储库保存方法尝试过的任何其他方式都不起作用。值得注意的是,我试图通过它的 id 从数据库中取回实体,然后更新它并保存,但这似乎没有提交。
非常感谢。
=============
你好内森。谢谢。它也不会在日志中更新。没有 UPDATE 指令只是 SELECT
这里是 application.properties 设置:
#==== connect to calanco ======#
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.use-new-id-generator-mapping=true
#temporary settings
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
=============
更新:Ken Chan 新年快乐;)我确实尝试从数据库中取回实体,更新并保存,但它不会持久保存到数据库中。
代码如下:
@Transactional
public void saveTemplatesFromDTOList(List<TemplateDTO> templateDTOList) {
for (TemplateDTO templateDTO : templateDTOList) {
Template templateFetchFromDB = templateRepo.getOne(templateDTO.getId());
EntityToDTOConverter.fillTemplateEntityFromTemplateDTO(templateDTO, templateFetchFromDB); // does update the fields from DTO to entity fetched from DB
templateRepo.save(templateFetchFromDB);
em.persist(templateFetchFromDB); //doesn't work
em.flush();
}
}
【问题讨论】:
-
您是否使用任何 ORM 工具,例如 hibernate。如果是,那么也显示配置文件。
-
你好。我相信 Spring Data 的“魔法”确实使用 Hibernate 作为基础。没有特殊的配置,只有注释(Spring Boot)。
-
你好,内森。谢谢。它也不会在日志中更新。没有 UPDATE 指令只是 SELECT
-
为什么不使用 JpaRepository 方法?
-
一段时间后返回。感谢 TinyOS。已经使用 Spring Data Repository。并且方法“save”在后台执行“EntityManager.persist”。老实说,不知道是什么解决了问题...
标签: java spring hibernate spring-boot spring-data