如果您碰巧将代码存储在 JNDI 中,则只需使用:DataSource
configuration.setProperty(
"hibernate.connection.datasource",
"java:comp/env/jdbc/yourDataSource");
但是,如果您使用像Apache DBCP或BoneCP这样的自定义数据源提供程序,并且您不想使用像Spring这样的依赖注入框架,那么您可以在创建之前将其注入:StandardServiceRegistryBuilder
SessionFactory
//retrieve your DataSource
DataSource dataSource = ...;
Configuration configuration = new Configuration()
.configure();
//create the SessionFactory from configuration
SessionFactory sf = configuration
.buildSessionFactory(
new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
//here you apply the custom dataSource
.applySetting(Environment.DATASOURCE, dataSource)
.build());
请注意,如果使用此方法,则无需再将连接参数置于休眠状态.cfg.xml。以下是使用上述方法时兼容的休眠.cfg.xml文件的示例:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="show_sql">false</property>
<!-- your mappings to classes go here -->
</session-factory>
</hibernate-configuration>
上面的代码在Hibernate 4.3上测试。