使用JPA / entityManager更新对象

时间:2017-01-19 14:03:02

标签: java jpa entitymanager hibernate-entitymanager

我有一个在Wildfly 10上运行的Java / Spring Web应用程序。我配置了JPA,并且想知道更新和删除语句的常用方法是什么。比如说,httprequest进入服务器以显示有关Person记录的所有详细信息。我将使用实体管理器来查找此记录

class PersonDao
{
    @PersistenceContent
    entityManager entityManager

    public Person findPerson(int id)
    {
         assert(id >= 0); //pseudocode

         Person p = this.entityManager.find(Person.class,id);

         assert(p != null); //pseudocode

         return p;
    }
}

然后屏幕上会显示此人的详细信息,请求已完成且线程已消失。在我的代码中不再可以访问实体管理器中附加的Person记录。

一段时间后,用户启动新请求以更新此人的年龄。目前在我的Dao课程中,我总是重新找到记录,所以我确信它存在于我的持久化环境中,但它似乎是冗余和乏味的。我想知道更好的方法来实现这个:

    public void updatePersonAge(int id, int newAge)
    {
         assert(newAge >= 0)

         Person p = this.findPerson(id);

         p.setAge(newAge);

         this.entityManager.persist(p);
    }

2 个答案:

答案 0 :(得分:1)

我这样做的方法是创建一个PersonRepository而不是PersonDao。 "Spring Data JPA for more info."

一旦你知道它,它很容易学习和很棒。你的Dao现在只是一个基于它的查询界面看起来像......

public interface PersonRepository extends JpaRepository<Person, Integer> { 
    //custom queries here...
}

即使您没有在此文件中放置任何内容,您现在也可以通过id创建,更新,查找,并从JpaRepository中删除所有内容。

然后我会创建一个PersonService来处理上述情况

@Service
public class PersonService {

    private PersonRepository personRepository        

    @Autowired
    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    // typically you would have create, findById and other methods here

    public void updatePersonAge(int id, int newAge) {
        assert(newAge >= 0)

        Person p = personRepository.findOne(id);

        p.setAge(newAge);

        personRepository.save(p);
   }

   // but if you want an easy way to do this and you can 
   // serialize the whole object instead of just get the id you can
   // simply call and update method
   public Person update(Person person) {
       assert(person.getId() != null);
       return personRepository.save(person);
   }

}

这假设您可以直接使用对象中已有的新时代序列化对象

此外,这可能不是您正在寻找的解决方案,因为我不直接使用实体管理器

答案 1 :(得分:0)

你这样做是正确的,打电话

Person p = this.findPerson(id);

获取正确的Person对象(再次)是必要的,因为正如您所描述的那样,实体管理器不再访问Person对象。