gpt4 book ai didi

java - JSF 2.0 和 hibernate 将新对象添加到 postgresql 数据库

转载 作者:行者123 更新时间:2023-11-30 05:09:58 25 4
gpt4 key购买 nike

我正在使用 Hibernate 和 Postgresql 数据库编写 JSF 2.0 应用程序。我的问题是对一次将数据插入多个表时如何处理 Hibernate session 的理解很差。我有一个方法 savePerson。该方法会根据用户提交的地址调用多次,但对象 Person 仅创建一次。然后方法 savePerson 调用方法 addAddress。代码如下所示:

public Person savePerson(Person p, String address) {

Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();

if (p == null) {
= new Person();

try {
tx = session.beginTransaction();
session.save(p);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {

tx.rollback();
} catch (HibernateException e1) {
}

throw e;
}
}
}

int id = p.getId();
addAddress(4, id, address);

return p;
}

方法addAddress:

public void addAddress(int table_id, int row_id, String address) {

Transaction tx = null;
session = HibernateUtil.getSessionFactory().openSession();
Address a = new Address(table_id, row_id, address);

try {
tx = session.beginTransaction();
session.save(a);
tx.commit();
} catch (RuntimeException e) {
System.out.println("first try");

if (tx != null && tx.isActive()) {
System.out.println("first try if");
try {
System.out.println("first try if try");

tx.rollback();
} catch (HibernateException e1) {

}
// throw again the first exception
throw e;
}
throw e;
}

但我收到以下错误:

org.hibernate.TransactionException: Transaction not successfully started

那么,当一次将数据插入多个表时,打开和关闭 session 的正确方法是什么?

最诚挚的问候,萨斯。

最佳答案

一个TransactionException 表示事务无法开始、提交或回滚。但提供完整的堆栈跟踪可能有助于完全理解问题。

话虽这么说,虽然您可以从单个 Session 创建多个(串行)Transaction,但在我看来,您的设计存在一个重大缺陷。如果您需要同时插入 PersonAddress,您很可能应该在单个工作单元中完成此操作。使用您当前的方法,添加 Address 可能会失败,并使新插入的 Person 处于不一致的状态。

So what is the proper way of opening and closing session when inserting the data into more than one table at a time?

在单个事务中完成此操作。

如果您想从方法中删除事务管理,您应该考虑使用 Open Session In View模式,如BalusC建议的。当然,除非您想要更细粒度的事务控制。

资源

关于java - JSF 2.0 和 hibernate 将新对象添加到 postgresql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3778325/

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