我们正在使用java配置Hibernate,这是我们配置hibernate的代码。
@Configuration
@EnableTransactionManagement
@ComponentScan({ "org.npcc.ccms.config" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
final static Logger logger = LogManager.getLogger(HibernateConfiguration.class);
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "org.npcc.ccms.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean(destroyMethod="")
public DataSource dataSource() {
JndiTemplate jndi = new JndiTemplate();
DataSource dataSource = null;
try {
dataSource = (DataSource) jndi.lookup(environment.getRequiredProperty("datasource"));
} catch (NamingException e) {
logger.error("NamingException for java:comp/env/jdbc/ccms_cp1_orcl", e);
}
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
我的问题是如何在同一个hibernate配置类中配置另一个数据源?我找到了解决方案here,但是使用xml配置,如何使用java配置?提前谢谢。
答案 0 :(得分:2)
您需要注释两个不同的bean,如下所示:
@Bean(name="SessionFactory")
public SessionFactory sessionFactory() {
}
和
@Bean(name="OtherSessionFactory")
public SessionFactory otherSessionFactory() {
}
两个数据源配置正确。
然后,当您想要使用其他SessionFactory时,您只需要:
@Autowired
@Qualifier("SessionFactory")
SessionFactory sessionFactory
或
@Autowired
@Qualifier("OtherSessionFactory")
SessionFactory sessionFactory