在hibernate3中,使用了c3p0连接池,尝试了多种办法取得connection对象,以下两种可以使用。

Java代码 
     Connection conn;  

    // 方法1:hibernate4中将要废弃这个方法
conn = session.connection(); // 方法2:这个方法也可以用,速度稍慢
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor)new Configuration().configure().buildSessionFactory();
conn = sessionFactory.getConnectionProvider().getConnection(); //方法:3
ConnectionProvider cp =((SessionFactoryImplementor)sessionFactory).getConnectionProvider();
cp.getConnection();

按hibernate的计划,4.0开始将除去Session.connection()这个方法,所以还是最好不要使用它了。
官方的替代方法是用Session.doWork();
如:

Java代码 
         getSession().doWork(
new Work() {
public void execute(Connection connection) {
// 这里已经得到connection了,可以继续你的JDBC代码。
// 注意不要close了这个connection。
}
}
);

另外一个方法:

package com.trendcom.base.util;

import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.web.context.ContextLoaderListener; public class DataSourceUtil { private static SessionFactory sessionFactory=null; static{
sessionFactory=(SessionFactory) ContextLoaderListener.getCurrentWebApplicationContext().getBean("sessionFactory");
} public static Connection getConnection(){
try {
return getDataSource().getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} public static void setSessionFactory(SessionFactory sessionFactory) {
DataSourceUtil.sessionFactory = sessionFactory;
} private static DataSource getDataSource() {
return SessionFactoryUtils.getDataSource(getSessionFactory());
} }

最新文章

  1. SSH整合,必出精品
  2. ThinkPHP3.2.3 跨域访问
  3. PHP集成百度Ueditor 1.4.3
  4. Python3 捕捉异常
  5. CSS3之边框样式(动画过渡)
  6. python 下划线的使用(转载:安生犹梦 新浪博客)
  7. hdu 3518(后缀数组)
  8. grub命令来引导linux
  9. mysql 服务意外停止1067错误解决办法小结
  10. javascript第十五课:DOM
  11. PHP显示超全局变量和显示程序执行时间
  12. ANSI标准
  13. c语言 创建链表
  14. 异常:Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException
  15. 基于layui和bootstrap搭建极简后台管理框架
  16. linux系统中日常运维常用命令汇总一
  17. 第14月第23天 uitextfield文字下移
  18. C#对Mongodb数组对象操作
  19. day2(基础数据类型)
  20. vue和微信小程序的区别、比较

热门文章

  1. gdb简明手册
  2. string字符串的一系列操作
  3. Windows8远程桌面CentOS 6.5
  4. 编写 unix和 windows的 Scala 脚本
  5. class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class
  6. RESTful的理解
  7. ( 译、持续更新 ) JavaScript 上分小技巧(二)
  8. POJ 2533 Longest Ordered Subsequence(最长上升子序列(NlogN)
  9. PTA fzu_oop_east
  10. IIS7.5