使用多个数据库进行休眠 [英] Hibernate using multiple databases
问题描述
有人知道如何在 hibernate 配置中添加另一个数据源,以及如何将 Spring 配置到该数据源并在我各自的 DAO 中自动注入吗?
Someone know how to add a another datasource in hibernate configuration and how to configure Spring to that datasource its autoinject in my respective DAO?
这是我使用一个数据源的代码,运行完美,但我不知道如何添加另一个数据源.我想添加另一个数据源,该数据源是具有与实际数据库不同的表的数据库.
This is my code with one datasource, that run perfectly, but i don't know how add another datasource. I want to add another data source that is a database with different tables than the actual database.
休眠配置
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url" value="jdbc:mysql://localhost/personal"/>
<property name="username" value="root"/>
<property name="password" value="mysql"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<property name="packagesToScan">
<list>
<value>com.app.personal.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
DAO 示例
@Repository
public class ModuloDAOHibernate extends HibernateTemplate implements ModuloDAO {
@Autowired
public ModuloDAOHibernate(SessionFactory sessionFactory) {
super(sessionFactory);
}
public List<Modulo> getAllGrupoModuloDAO() {
Criteria criteriaList = this.getSession().createCriteria(Modulo.class);
criteriaList.addOrder(Order.asc("orden"));
return criteriaList.list();
}
推荐答案
ok.我找到了另一个解决方案,那就是使用与这样相同的方法:添加另一个数据源和会话工厂,然后在注入 sessionFactory 的 DAO 方法中添加 @Qualifier 注释以及所需的 sessionFactory 的属性,如下所示:
ok. I find another solution, and that is using the same method like this: add another dataSource and SessionFactory, next in the method of DAO that injject the sessionFactory add the @Qualifier anottation withe the property of the sessionFactory required, like this:
@Autowired
public ProgramaSgteDAOHibernate(@Qualifier("sessionFactory3") SessionFactory sessionFactory) {
super(sessionFactory);
}
这篇关于使用多个数据库进行休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!