I am encountering an issue while attempting to invoke Cannot invoke “jakarta.persistence.EntityManager.createQuery(String, java.lang.Class)” in my java application. The error message indicates that “this.em” is null causing the invocation to fail.
I’d appreciate guidance on resolving this error related to the null EntityManager
when invoking createQuery(String, Class)
.
@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
public class ApplicationConfig {
@PersistenceUnit
private EntityManagerFactory emf;
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.project.repository");
factory.setDataSource(dataSource());
return factory;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory);
return txManager;
}
}
@Repository
public class StudentSystemRepository{
@PersistenceContext
private EntityManager em;
public List<Student> findAll(){
String jpql = "SELECT t FROM Student t ";
TypedQuery<Student> query = em.createQuery(jpql, Student.class);
return query.getResultList();
}
}