Rajesh Rajesh - 3 months ago 22
Java Question

How to use @Qualifier in Hibernate

My hibernate configuration class is below.

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.span.vms.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
@Primary
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.span.vms.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}

@Bean
public LocalSessionFactoryBean sessionFactoryActiviti() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSourceActiviti());
sessionFactory.setPackagesToScan(new String[] { "com.span.vms.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}

@Bean(name = "dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}

@Bean(name = "dataSourceActiviti")
public DataSource dataSourceActiviti() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.activiti.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
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;
}
}


When I run this via spring boot I am getting error saying "expected single matching bean but found 2: datasource and dataSourceActiviti".

I added name to each bean. But how can use @Qualifier here?

Answer

You can make one of the DataSource primary by annotating it with @Primary.

Comments