Hibernate 连接信息的读取

公司的报表需要使用 connection ,同事使用的是建立一个类来获得Connection对象。如下:

 

public class JDBCConnection {
 

 public static String driver = "com.mysql.jdbc.Driver";

 public static String url = "jdbc:mysql://192.168.4.52/cms";

 public static String user = "root";

 public static String password = "password";


  public static Connection getConnection() throws ClassNotFoundException,
   SQLException {
  
  Class.forName(driver);
  Connection conn = DriverManager.getConnection(url, user, password);
    return conn;
 }


}

我们现在使用的是 Hibernate,这样的话,修改数据源不方便。

我开始使用了直接从Hibernate当中返回Connection,如下:

 

 Session session = HibernateSessionFactory.getSession();  
  try {
   conn = session.connection();
  } catch (Exception e) {
   throw new HibernateException(e);
  } finally {
   HibernateSessionFactory.closeSession();
  }

 

但是发现该数据源无法给报表系统正常使用,

最后想:干脆Connection还是使用他原来的方式。就连接信息从Hibernate当中读取。

最后修改成了如下方式:


  Properties properties = HibernateSessionFactory.getConfiguration().getProperties();
  
  String driver = properties.getProperty("connection.driver_class");//"com.mysql.jdbc.Driver";

  String url = properties.getProperty("connection.url");//"jdbc:mysql://192.168.4.52/cms";

  String user = properties.getProperty("connection.username");//"root";

  String password = properties.getProperty("connection.password");//"password";
  
  
  Class.forName(driver);
  Connection conn = DriverManager.getConnection(url, user, password);
  

运行成功!

 

如果大家有没有什么更好的方法解决,请回复我。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值