gpt4 book ai didi

java - hibernate ,合并时遇到问题

转载 作者:行者123 更新时间:2023-12-01 11:07:18 24 4
gpt4 key购买 nike

我正在尝试从我的 servlet 更新数据库中的对象。但是它成功运行,没有任何错误,但没有删除。

我的 HibernateUtil 看起来像:

public class HibernateUtil {

private static SessionFactory sessionFactory;
private static final String HIBER = "hibernate.cfg.xml";

public HibernateUtil() {
try {
sessionFactory = new Configuration().addResource(HIBER).configure()
.buildSessionFactory();
} catch (HibernateException ex) {
System.out.println(ex);
}
}

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void closeSessionFactory() {
sessionFactory.close();
}
}

我在 servlet 初始化时实例化上面的类。

@Override
public void init() {

hiber = new HibernateUtil();
System.out.println("Servlet Initialized");
}

我之前使用过 openSession,并了解到对于 Web 应用程序使用 getCurrentSession 更好,现在我正在尝试重新进行。

String add = request.getParameter("houseId");
hiber.getSessionFactory().getCurrentSession();
Transaction tx = session1.beginTransaction();

House house = (House) session1.get(House.class, Long.parseLong(add));

System.out.println(house.getAddress());

SessionUser.getHouses().add(house);

session1.merge(SessionUser);
tx.commit();
session1.close();

System.out.println(house.getAddress());

我用更简单的方式编辑了我的故障代码。我只是不知道为什么这不起作用。

最佳答案

请提交事务并关闭 session 。

  String add = request.getParameter("Id");
Session session1 = hiber.getSessionFactory().getCurrentSession();
Transaction tx;
try {
tx = session1.beginTransaction();
for (Iterator<House> iterator = SessionUser.gethouse().iterator(); iterator.hasNext();) {
House house = iterator.next();
if (house.getProjectId() == Long.parseLong(add)) {
iterator.remove();
session1.remove(house);
session1.flush();
}
}

session1.merge(SessionUser);
tx.commit();

} catch (Exception e) {
System.out.println(e);
} finally {
System.out.println("______");
session1.close();
}

关于java - hibernate ,合并时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807659/

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