当存在 2 个数据源时,始终选取第一个数据源



我在websphere上使用Spring和Hibernate,并试图对数据库进行查询。我在导入的 2 个不同项目中有 2 个数据源,我的问题是我只选择了一个数据源。以下是每个项目的休眠 XML:

项目1:

<tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="DbSource1" />
        <property name="mappingResources">

项目2:

<bean id="SessionFactory2" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="DbSource2" />
    <property name="mappingResources">

-- 还有用于存储过程的 JDBC 模板

  <bean id="retrievalService" class="xx.xx.xx.JDBCRetrievalService">
    <property name="jdbcTemplate" ref="jdbcTemplate" />   </bean>
  <bean id="transactionalService" class="xx.xx.xx.JDBCTransactionalService">
    <property name="jdbcTemplate" ref="jdbcTemplate" />   </bean>

In my project application context, I simply import the 2 xmls above 
<import resource="classpath:DBsource-hibernate1.xml" />
  <import resource="classpath:DBSource-hibernate2.xml" />

现在在我的代码中,我有以下内容:

public abstract class HibernateBaseDao implements Serializable {
    private static final long serialVersionUID = -8688473006487128511L;

    /** Hibernate Session factory. */
    @Qualifier("SessionFactory2")
    private SessionFactory sessionFactory;

    protected HibernateBaseDao() {
        this.sessionFactory = null;
    }

    protected SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return sessionFactory != null ? sessionFactory.getCurrentSession() : null;
    }
}
@Component("MyDao")
public class MyDaoImpl
    extends HibernateBaseDao
    implements MyDaoI{
@Override
public int getValueFromDatabase(){
   SQLQuery sqlQuery =  (SQLQuery) createSQLQuery("select uservalue from MyTable");
   List<Integer> values= sqlQuery.list();
   values.get(0);
}
}

最后,这是我调用它的代码:

@Autowired我的道米道;

    @Override
@Transactional()
public void runQuery() throws Exception
{
      myDao.getValueFromDatabase
    }

它返回的问题说不存在表。经过调查,我发现它正在选择第一个数据源。因此,我已经拉了两天的头发。有什么建议吗???我已经在我正在扩展的基类中拥有 SessionFactory2 的限定符

非常感谢

您的问题是您没有在属性中注入 SessionFactory2。 @Qualifier本身什么都不做,则需要添加@Autowire

解决方案是:

/** Hibernate Session factory. */
    @Autowire
    @Qualifier("SessionFactory2")
    private SessionFactory sessionFactory;

此外,您不需要 getter/setter 在私有属性上使用 @Autowired ;)

最新更新