我想在Spring Boot应用程序中使用preparestatement插入一些记录。因此,我已经使用hibernate建立了数据库连接(HibernateConfig-仅用于数据库连接)。由于我要使用PreparedStatement,因此我需要Hibernate Connection
或SessionFactory
中的Session
。
[我知道,使用getCurrentSession时,将为休眠操作(例如session.beginTransaction()和session.save()等)管理事务管理本身>
我的问题是我是否需要关闭连接和其他东西,使用sessionFactory.getCurrentSession()
时显式地在finally块中。
在DAOImpl文件中
@Repository @Transactional public class TestDAOImpl implements TestDAO { @Autowired private SessionFactory sessionFactory; public Connection getConnection(){ Session session = sessionFactory.getCurrentSession(); Connection conn = session.doReturningWork(new ReturningWork<Connection>() { @Override public Connection execute(Connection conn) throws SQLException { return conn; } }); return conn; } public void insertRecords() { Connection conn= getConnection(); PreparedStatement ps = null; try { String inserQuery ="INSERT IN TO TEST VALUES(?,?,?)" //some insert statement conn.setAutoCommit(false); ps = conn.prepareStatement(inserQuery); //set values ps.setString() and ps.addBatch(); -some code here int[] insertCounts = ps.executeBatch(); conn.commit(); } catch(BatchUpdateException e){ } catch(SQLException e){ } finally { if(ps!=null)ps.close(); if(conn!=null) conn.close(); if(sessionFactory!=null) sessionFactory.close(); } }
[请注意,我在同一DAOImpl类中使用了3个以上的方法,并为每个方法
Connection conn= getConnection();
创建连接并在finally块中关闭
也请让我知道最佳实践或从SessionFactory获得连接的任何其他替代方法。
我想在Spring Boot应用程序中使用preparestatement插入一些记录。因此,我已经使用hibernate建立了数据库连接(HibernateConfig-仅用于数据库连接)。因为我要去...
是的,您必须明确地关闭连接,以防止内存泄漏。最好的方法也是try-with-resources语句,该语句会自动关闭您在其中打开的可关闭资源。