gpt4 book ai didi

java - Hibernate:更新一个对象 -> 也执行不需要的删除语句

转载 作者:行者123 更新时间:2023-11-30 09:51:55 24 4
gpt4 key购买 nike

我在我的 Java 应用程序中使用 Hibernate 作为 ORM。我有一个 Project <-> Person manytomany-relation 并且该项目是映射所有者。

现在我遇到了问题,我想更新项目。该项目有一个 ID、一个名称……和一组人员。做update,Project_Person联表中的人都被删除了,控制台SQL语句:

Hibernate: update Project set description=?, name=? where id=?
Hibernate: delete from Project_Person where project_id=?

但我不希望删除语句被执行。

我的 Java 应用程序中有这个:

this.projService.updateProject(p);

其中 p 是项目,但采用 POJO 方式,没有 Set of Persons。所以我想,为了使其“Hibernate-ready”,我在一个单独的事务中将其设置为 findProjectById,因此我从数据库中获取项目:

Project proj = this.projService.findProjectById(p.getId());
proj.setName(p.getName());
proj.setDescription(p.getDescription());

所以我得到了 Hibernate-ready Project 对象,更改了值,然后告诉他更新项目。但是 Set 在调试器 View 中是一个 PersistentSet 并且其中没有 Persons(我认为,因为它们是延迟加载的)。但是更新一个

session.update(p);

在新事务中,我得到了更新语句和不需要的删除语句。如何避免删除语句?

我是否必须创建一个特殊的 SQL 语句,以便只更新我要更新的数据库表字段?还是有其他/更好的解决方案?

最好的问候。


更新这会抛出一个 LazyInitializationException:

public Project findProjectById(int projectId) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session sess = sessionFactory.getCurrentSession();
Transaction tx = sess.beginTransaction();
try {
Project project = (Project)sess.createQuery("from Project where id = "+projectId).list().get(0);
tx.commit();
System.out.println(project.getPersons().size());
return project;
} catch (IndexOutOfBoundsException ex) {
return null;
}
}

调试器的屏幕截图:

http://img94.imageshack.us/img94/2020/screendebugger.png

hibernate 工具

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
// SessionFactory of Hibernate
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed. " + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

tx.commit() 之前的屏幕截图

http://img808.imageshack.us/img808/9624/screendebugger2.png

最佳答案

这意味着(如您所建议的)您的 Collection 是空的。但这不是由于延迟加载 - 调试器将允许您加载集合。也许由于其他原因它是空的。通过显示 collection.size() 来确认这一点。

问题的另一部分是级联。如果您已定义级联 delete-orphan,则将其删除,或确保集合实际已填满。

关于java - Hibernate:更新一个对象 -> 也执行不需要的删除语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4452759/

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