gpt4 book ai didi

java - Spring Data 未提交给 DB

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:54 26 4
gpt4 key购买 nike

我想知道通过 Spring Data 从 DTO 转换为 DataBase 的最佳实践是什么?

这是我迄今为止尝试过的:

    @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();
}
}

最佳答案

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

正确的方法是使用 entityManager 获取需要 update 的实体,然后通过调用其方法来更新其值。当事务提交时,您在实体中所做的更改将更新到数据库。请注意,您不需要调用 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......

}

关于java - Spring Data 未提交给 DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54023687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com