gpt4 book ai didi

java - 无法使用 jpa 更新对象

转载 作者:行者123 更新时间:2023-12-01 22:45:02 26 4
gpt4 key购买 nike

我在更新记录时遇到问题:

package legacy.database;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

public class Queries {

private static final Logger log = Logger.getLogger(Queries.class.getName());
private final EntityManagerFactory emf = Persistence.createEntityManagerFactory("LegacyDatabasePU");
private final EntityManager em = emf.createEntityManager();

public Queries() {
}

private List<Clients> findAll() {
Query q = em.createQuery("select c from Clients c");
List<Clients> clients = q.getResultList();
return clients;
}




public Clients findById(int id) {
Clients client = em.find(Clients.class, id);
return client;
}


public void update(Clients c2) {
Clients c1 = em.find(Clients.class, c2.getId());
java.util.Date date = new java.util.Date();
Timestamp t = new Timestamp(date.getTime());
c2.setDateUpdated(t.toString());
em.getTransaction().begin();
c2.setDateUpdated(t.toString());
c1 = c2;
log.info(c1.getNotes());
log.info(c2.getNotes());
em.getTransaction().commit();
}
}

分配c1=c2有问题吗?我是否必须手动检查 c1 并更新每条记录?

最佳答案

在事务中执行 find(),然后在事务中调用您的变异方法。然后提交将自动更新对象。只需简单移动 begin txn 即可实现这一点。只有您知道各种更新是什么,因此不会尝试清理它

try
{
em.getTransaction().begin();

Clients c1 = em.find(Clients.class, c2.getId());
Timestamp t = new Timestamp(new java.util.Date().getTime());
c2.setDateUpdated(t.toString());
c1 = c2;
log.info(c1.getNotes()); log.info(c2.getNotes());

em.getTransaction().commit();
}
finally
{
if (em.getTransaction().isActive())
{
em.getTransaction().rollback();
}
}

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

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