0

Description

when i try to persist an object with the help of the entity manager it seems that the entity manager is null, not instantiated even though i used the annotation (@PersistenceContext)!

any recommendations?

Entity Manager

@Repository
@Transactional
public class ImplEmployee implements EmployeeInterface{

    @PersistenceContext
    EntityManager manager;

    @Override
    public void  save(Employee employee) {
        manager.persist(employee);      
    }
    //other methods...

Main

@SpringBootApplication
public class JpaSpringApplication {

public static void main(String[] args) {
    SpringApplication.run(JpaSpringApplication.class, args);
    
    Employee e = new Employee();
    
    e.setId(4444);
    e.setName("Nathan");
    e.setSalary(543.87);
    
    ImplEmployee i = new ImplEmployee();
    i.save(e);
            
   }
 }

output

 Exception in thread "main" java.lang.NullPointerException: Cannot invoke 
 "javax.persistence.EntityManager.persist(Object)" because "this.manager" is null
 at com.spring.jpa.demo.implemployee.ImplEmployee.save(ImplEmployee.java:25)
 at com.spring.jpa.demo.main.JpaSpringApplication.main(JpaSpringApplication.java:19)

1 Answers1

1

Because of this line: ImplEmployee i = new ImplEmployee(); there is no ImplEmployee in the application context.

You should autowire ImplEmployee:

@SpringBootApplication
public class JpaSpringApplication implements CommandLineRunner  {
    
    public static void main(String[] args) {
        SpringApplication.run(JpaSpringApplication.class, args);
    }
    
    @Autowired
    ImplEmployee implEmployee;

    @Override
    public void run(String... args) throws Exception {
        Employee e = new Employee();
    
        e.setId(4444);
        e.setName("Nathan");
        e.setSalary(543.87);
    
        implEmployee.save(e);
    }
}

Making an @Autowired field static is not a good idea. You can use the way above. A better approach is to create an EmployeeService class with @Service annotation. Then the same way you can autowire ImplEmployee and save the record in a method like saveEmployee().

Hülya
  • 3,353
  • 2
  • 12
  • 19