Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在@Transactional中持久化后编辑@Entity?_Java_Spring_Hibernate_Jpa - Fatal编程技术网

Java 在@Transactional中持久化后编辑@Entity?

Java 在@Transactional中持久化后编辑@Entity?,java,spring,hibernate,jpa,Java,Spring,Hibernate,Jpa,首先保存新的@实体,然后在相同的@事务性方法中编辑它是否有效 @Autowired private PersonRepository dao; //extends CrudRepository<Person, Long> @Transactional public Person createUpdatePerson(PersonDTO dto) { Person entity = dao.find(dto.getId()); if (entity == null) {

首先保存新的
@实体
,然后在相同的
@事务性
方法中编辑它是否有效

@Autowired
private PersonRepository dao; //extends CrudRepository<Person, Long>

@Transactional
public Person createUpdatePerson(PersonDTO dto) {
   Person entity = dao.find(dto.getId());
   if (entity == null) {
      entity = new Person();
      dao.save(entity);     
   }

   //merge update
   entity.setName(dto.getName()); 
   entity.setAge(dto.getAge());
   //etc

   return entity;
}
@Autowired
私人人格//积垢沉积
@交易的
公众人物createUpdatePerson(PersonDTO dto){
personentity=dao.find(dto.getId());
if(实体==null){
实体=新人();
保存(实体);
}
//合并更新
entity.setName(dto.getName());
entity.setAge(dto.getAge());
//等
返回实体;
}

这样做有效吗?

您可以保存实体并在之后进行更新,但不会保存您的更新。您应该再次保存实体。最佳解决方案是:

@Transactional
public Person createUpdatePerson(PersonDTO dto) {
   Person entity = dao.find(dto.getId());
   if (entity == null) {
      entity = new Person();
   }

   //merge update
   entity.setName(dto.getName()); 
   entity.setAge(dto.getAge());
   //etc
   return dao.save(entity);
}
这是积垢的保存实现

@Transactional
public <S extends T> S save(S entity) {
        if (entityInformation.isNew(entity)) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
}
@Transactional
公共存储(S实体){
if(entityInformation.isNew(实体)){
em.persist(实体);
返回实体;
}否则{
返回em.merge(实体);
}
}

它已经是事务性的,同时将实体保存到hibernate中。然后它会被刷新到数据库中

这取决于“道·存”的作用。只要对象仍处于“托管”状态,那么yes
entity framework
.net
,您就应该删除此标记。@NeilStockton它扩展到Crudepository上,它不能在通过setters保存后仅更新对象。因为我不知道什么是“Crudepository”,所以我仍然不知道调用后对象处于什么状态。如果对象是“托管”的,那么对setter的调用将在事务性方法的末尾持久化。。。无需再打电话给em。persist@NeilStockton所以我调用
dao.save()实际上并没有什么坏处
即使
@Transactional
关心如何合并现有实体?@Transactional注释的主要目的是在异常情况下回滚更改,并在事务处于“只读”模式时防止数据更改。将其用于其他目的是不安全的。