In a training Spring MVC + JPA/Hibernate project, I'm getting the error in question, after I've changed my configuration.
Originally the DAO class was like this:
public Course getById(Integer id) throws DAOException {
Course result = null;
try {
EntityManager em = emf.getFactory().createEntityManager();
result = em.find(Course.class, id);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new DAOException("Could not get Course By Id", e);
}
return result;
}
I was told to spawn EntityManager with @PersistenceContext, and avoid creating new EntityManager every now and then. So I replaced the above EntityManager em = ... line with a @Autowired EntityManager em; field, and changed the JpaConfig class, so it looks like:
@Configuration
@ComponentScan(basePackages = "com.example.school")
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
public class JpaConfig {
private final Environment environment;
@Autowired
public JpaConfig(Environment environment) {
this.environment = environment;
}
@Autowired
DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.school");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
While previously the configuration file was that simple:
@Configuration
public class EntityManagerConfig {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU");
@Bean
EntityManager em() {
return emf.createEntityManager();
}
}
Now I get a stacktrace with the following most important problem in it:
org.springframework.beans.factory.UnsatisfiedDependencyException ...
...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'courseDAO' is expected to be of type 'com.example.school.dao.CourseDAO' but was actually of type 'com.sun.proxy.$Proxy49' at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1317)
What can be wrong about this configuration?