'How can I autowire an EntityManager into my repository without it being always null?
I have a multi-module spring project. In one of my modules I have a repository that executes native queries in my database. To achieve that I'm using an Autowired EntityManager.
The problem is that EntityManager is always null in my repository. I'm not sure if I should configure the EntityManager anywhere, but I expected Spring to be able to inject it into my repository without that.
Error message:
java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager.createNativeQuery(String)" because "this.entityManager" is null
What I have already tried:
- Using @PersistenceContext instead of @Autowired
- Adding @EnableJpaRepositories, @EntityScan, @ComponentScan into the MainApplication class to force Spring to scan my classes in the other module.
Here is my project tree: (Some files are omitted because they are probably not relevant)
MyApp/
├─ Application/
│ ├─ com.application/
│ │ ├─ MainApplication.java
├─ Module/
│ ├─ com.myModule/
│ │ ├─ service/
│ │ │ ├─ ProcedureService.java
│ │ ├─ repository/
│ │ │ ├─ IProcedureRepository.java
│ │ │ ├─ ProcedureRepository.java
MainApplication.java
@SpringBootApplication(
scanBasePackages = {
"com.myModule", "com.Application"
})
@EnableJpaRepositories(basePackages = { "com.myModule" })
@EntityScan(basePackages = { "com.myModule" })
@ComponentScan(basePackages = { "com.myModule" })
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
ProcedureService.java
@Service
public class ProcedureService implements IProcedureService {
@Autowired
IProcedureRepository repository;
@Override
@Transactional
public void executarQueryTeste() {
repository.executarQueryComParametros(query here);
}
ProcedureRepository.java
@Repository
public class ProcedureRepository implements IProcedureRepository {
@Autowired
EntityManager entityManager;
@SafeVarargs
@Override
public final void executarQueryComParametros(String query){
var entityManagerQuery = entityManager.createNativeQuery(query);
entityManagerQuery.executeUpdate();
}
}
What should I do to be able to access my EntityManager?
Solution 1:[1]
In my case the problem was the final keyword in my repository method. Removing it made it possible to access my autowired EntityManager.
@Repository
public class ProcedureRepository implements IProcedureRepository {
@Autowired
EntityManager entityManager;
@Override
public void executarQueryComParametros(String query){
var entityManagerQuery = entityManager.createNativeQuery(query);
entityManagerQuery.executeUpdate();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gustavo Cesário |
