springMVC新增第二个数据源在java代码中通过SessionFactory实现分页查询第二个数据源中表的数据
首先需要在Spring配置文件中配置第二个数据源和SessionFactory:
<!-- 数据源配置 -->
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db2"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- SessionFactory配置 -->
<bean id="sessionFactory2" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource2"/>
<property name="mappingResources">
<list>
<value>com/example/entity/Entity2.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.jdbc.batch_size">30</prop>
</props>
</property>
</bean>
然后在Java代码中注入第二个数据源的SessionFactory:
@Autowired
@Qualifier("sessionFactory2")
private SessionFactory sessionFactory2;
接下来可以在Java代码中,使用第二个数据源的SessionFactory实现分页查询第二个数据源中的表数据:
public List<Entity2> findEntity2List(int pageNo, int pageSize) {
Session session = sessionFactory2.getCurrentSession();
Query query = session.createQuery("from Entity2");
query.setFirstResult((pageNo - 1) * pageSize);
query.setMaxResults(pageSize);
return query.list();
}
``
原文地址: https://www.cveoy.top/t/topic/eBTc 著作权归作者所有。请勿转载和采集!