hibernate创建了很多连接

tjvv9vkg  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(347)

我使用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();
        }
    }
}
qlfbtfca

qlfbtfca1#

在所提供的 DBManager 班级。

efzxgjgh

efzxgjgh2#

下面是一些示例代码,说明如何正确处理事务:

Transaction tx = session.beginTransaction();
try {
    session.save(dropTarget);
    tx.commit();
} catch (RuntimeException e) {
    if (tx.isActive()) tx.rollback();
    throw e;
}

您可以创建一个简单的助手函数,如下所示:

public static <T> T runInTransaction(Session session, Function<Session, T> task) {
  Transaction tx = session.beginTransaction();
  try {
    T res = task(session);
    tx.commit();
    return res;
  } catch (RuntimeException e) {
    if (tx.isActive()) tx.rollback();
    throw e;
  }
}

在你的代码中这样使用:

runInTransaction(session, s -> s.save(dropTarget));

相关问题