gpt4 book ai didi

java - 使用 JPA/entityManager 更新对象

转载 作者:行者123 更新时间:2023-12-01 09:00:08 25 4
gpt4 key购买 nike

我有一个在 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;
}
}

然后这个人的详细信息就会显示在屏幕上,请求完成,线程消失。在我的代码中无法再访问实体管理器中附加的人员记录。

一段时间后,用户发起一个新请求来更新该人的年龄。目前,在我的 Dao 类中,我总是重新查找记录,因此我确信它存在于我的持久性上下文中,但它似乎是多余且乏味的。我想知道更好的方法来实现这个:

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

Person p = this.findPerson(id);

p.setAge(newAge);

this.entityManager.persist(p);
}

最佳答案

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

学习起来很简单,一旦你了解了它,就会觉得非常棒。您的 Dao 现在只是一个接口(interface),基于它的查询看起来像......

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

}

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

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

关于java - 使用 JPA/entityManager 更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743682/

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