我使用hibernate+springboot,db是mysql,两天后就有了从150到250的大量连接。这是我的bean,它与实体和db交互。我想我会处理所有的异常并关闭所有的连接
package com.root.lvrmmonitor.utils;
import com.root.lvrmmonitor.entities.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DBManager {
public List<Item> getItemsList() {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Item", Item.class).list();
}
}
public DropTarget saveDropTarget(DropTarget dropTarget) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
session.save(dropTarget);
tx.commit();
}
return dropTarget;
}
public void deleteDropTarget(DropTarget dropTarget) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
session.delete(dropTarget);
tx.commit();
}
}
public void saveSuccess(Success success) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
session.save(success);
tx.commit();
}
}
}
2条答案
按热度按时间qlfbtfca1#
在所提供的
DBManager
班级。efzxgjgh2#
下面是一些示例代码,说明如何正确处理事务:
您可以创建一个简单的助手函数,如下所示:
在你的代码中这样使用: