为什么尽管使用了@PersistenceContext Annotation,实体管理器却没有被spring注入



描述

当我试图在实体管理器的帮助下持久化一个对象时,实体管理器似乎为null,即使我使用了注释(@PersistenceContext(,也没有实例化!

有什么建议吗?

实体经理

@Repository
@Transactional
public class ImplEmployee implements EmployeeInterface{
@PersistenceContext
EntityManager manager;
@Override
public void  save(Employee employee) {
manager.persist(employee);      
}
//other methods...

@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);

}
}

输出

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)

因为这一行:ImplEmployee i = new ImplEmployee();,所以应用程序上下文中没有ImplEmployee

您应该自动连接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);
}
}

制作一个@Autowired字段static不是一个好主意。你可以用上面的方法。一种更好的方法是创建一个带有@Service注释的EmployeeService类。然后以同样的方式,您可以自动连接ImplEmployee并用类似saveEmployee()的方法保存记录。

最新更新