【问题标题】:Spring Data not committing to DBSpring Data 未提交到 DB
【发布时间】: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


【解决方案1】:

merge() 仅适用于 @Entity 实例。它不适用于DTO

正确的方法是使用entityManager获取需要更新的实体,然后调用其方法更新其值。当事务提交时,您在实体中所做的更改将更新到数据库。请注意,您无需致电merge() 进行更新,我注意到许多男孩做错了。 merge() 用于将分离的实体更新回数据库,这是另一回事。

因此,更新一个 DTO 的一般流程如下所示(请针对练习的列表版本进行修改:D)

@Transactional
public void saveTemplatesFromDTO(TemplateDTO dto) {
    Template template = em.find(Template.class , dto.getTemplateId());

    //Get DTO value to update template
    template.setFoo(dto.getFoo());
    template.setBar(dto.getBar());
    //blablabla......

}

【讨论】:

  • 新年快乐 ;) 我确实尝试从数据库中取回实体,对其进行更新并保存,但它不会保留在数据库中。这是代码:
  • 新年快乐~那么很可能是因为你没有配置事务属性。至少,你必须在你的spring boot配置中@EnableTransactionManagement并定义PlatformTransactionManager.... ..
  • 感谢 Ken Chan 的时间。现在工作(编辑了 OQuestion)。好像不需要配置事务吧
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
相关资源
最近更新 更多