Issue
I have a spring boot application. It creates LocalSessionFactoryBean Object and inject into session factory variable. It works fine as follow:
@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;
@Primary
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan(
new String[] {
"com.abc..entities",
"com.abc.xyz.entities",
"
});
factory.setHibernateProperties(hibernateProperties());
return factory;
}
However, I need to change bean Name of sessionFactory, which is default as function name, from sessionFactory to entityManagerFactory, so I did following:
@Autowired
@Qualifier(value="entityManagerFactory")
private SessionFactory sessionFactory;
@Primary
@Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan(
new String[] {
"com.abc..entities",
"com.abc.xyz.entities",
"
});
factory.setHibernateProperties(hibernateProperties());
return factory;
}
But it throws error:
> Error creating bean with name 'XYZ': Unsatisfied dependency expressed
> through field 'sessionFactory'; nested exception is
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type 'org.hibernate.SessionFactory' available:
> expected at least 1 bean which qualifies as autowire candidate.
> Dependency annotations:
> {@org.springframework.beans.factory.annotation.Autowired(required=true),
> @org.springframework.beans.factory.annotation.Qualifier(value=entityManagerFactory)}
I believe i did it correctly, what did I miss here?
Update :-
I tried following as mentioned in one of answer but it did not work:
@Autowired
@Qualifier(value = "entityManagerFactory")
private SessionFactory sessionFactory;
and changed method as
@Primary
@Bean
public LocalSessionFactoryBean entityManagerFactory()
{ ..........},
> Unsatisfied dependency expressed through field 'sessionFactory';
> nested exception is
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type 'org.hibernate.SessionFactory' available:
> expected at least 1 bean which qualifies as autowire candidate.
> Dependency annotations:
> {@org.springframework.beans.factory.annotation.Autowired(required=true),
> @org.springframework.beans.factory.annotation.Qualifier(value=entityManagerFactory)}
Solution
What I think that happens here, is that entityManagerFactory is automatically registered from spring for another bean. Therefore you don't get what you ask for.
Try changing a little bit the name
@Bean(name="customEntityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
and then
@Autowired
@Qualifier("customEntityManagerFactory")
private SessionFactory sessionFactory;
Answered By - Panagiotis Bougioukos