How can I set Datasource when I'm creating Hibernate SessionFactory?

后端 未结 8 409
星月不相逢
星月不相逢 2020-12-02 17:17

I\'m creating SessionFactory and I have my datasource as object in code where I\'m creating SessionFactory, but i cannot set datasource to Hibernate Configuration object. So

8条回答
  •  抹茶落季
    2020-12-02 18:05

    If your datasource is bounded at the JNDI tree:

    configuration.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test");
    

    Otherwise, if you have a DataSource object in code, which you want to use:

    java.sql.Connection conn = datasource.getConnection();
    Session session = sessionFactory.openSession(conn);
    

    I would recommend the first one, to let Hibernate handle the connection lifecycle as needed. At the second approach, make sure that you close the connection when it's no longer needed.

提交回复
热议问题