java.lang.NullPointerException : Cannot invoke "javax. persistence.EntityManager error in Spring MVC while pulling data

标签 java spring hibernate entitymanager

我正在尝试学习在不使用 springboot 的情况下使用 spring mvc 和 Hibernate 创建 ReST API 端点。当我运行我的终点时,我收到内部服务器错误提示,

java.lang.NullPointerException:无法调用“javax.persistence.EntityManager.createQuery(String, java.lang.Class)”,因为“this.entityManager”为空

我在src/main/webapp/web-1nf下的spring-servlet.xml文件是这样的,

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<annotation-driven />

<resources mapping="/resources/**" location="/resources/" />

<beans:bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="org.postgresql.Driver" />
    <beans:property name="url" value="jdbc:postgresql://localhost:5432/company" />
    <beans:property name="username" value="postgres" />
    <beans:property name="password" value="postgresql" />
    <!--<property name="socketTimeout" value="10"/>-->

    <beans:property name="connectionProperties">
        <beans:props>
            <beans:prop key="socketTimeout">10</beans:prop>
        </beans:props>
    </beans:property>
 </beans:bean>


<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <beans:property name="dataSource" ref="dataSource" />
 <beans:property name="annotatedClasses">
 <beans:list>
 <beans:value>com.springmvc.Employee</beans:value>
</beans:list>
</beans:property>

<beans:property name="hibernateProperties">
 <beans:props>
   <beans:prop 
     key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
   </beans:prop>
  <beans:prop key="hibernate.show_sql">true</beans:prop>
 </beans:props>
</beans:property>
</beans:bean>

<context:component-scan base-package="com.springmvc" />


<tx:annotation-driven transaction-manager="transactionMgr"/>

 <beans:bean id="transactionMgr" 
  class="org.springframework.orm.jpa.JpaTransactionManager">
   <beans:property name="entityManagerFactory" ref="mgrFactory"/>
 </beans:bean>

   <beans:bean id="mgrFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
   <beans:property name="dataSource" ref="dataSource"/>
   <beans:property name="packagesToScan" value="com.springmvc"/>
    <beans:property name="jpaVendorAdapter">
      <beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
   </beans:property>
   <beans:property name="jpaProperties">
      <beans:props>
        <beans:prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</beans:prop>
        <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
        <beans:prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</beans:prop>
        <beans:prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</beans:prop>
        <beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
        <beans:prop key="hibernate.format_sql">${hibernate.format_sql}</beans:prop>
    </beans:props>
   </beans:property>
 </beans:bean>

</beans:beans>

我的 Controller 是,

@RestController
@RequestMapping("/mvchibernate")
public class CompanyController {

@Autowired
EmployeeService employeeService;

 @GetMapping(value = "/getAllEmployees")
    public List<Employee> getEmployeesList() {
     
     @SuppressWarnings("unchecked")
    List<Employee> listOfEmployees = employeeService.getAllEmployees();
        return listOfEmployees;
    }
}

我的服务类如下,

@Service
public class EmployeeService {

@Autowired
EmployeeDAO employeeDaoObj;

public List getAllEmployees() { 
    return employeeDaoObj.getAllEmployees();
  }
}

和 DAO 实现,

@Repository
public class EmployeeDAO {

@PersistenceContext private EntityManager entityManager;

public List<Employee> getAllEmployees() {
    
    String jpql = "SELECT e FROM Employee e";
    TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
    
       return query.getResultList();
    
        }
}

在我的 DAO 类中,我自动连接了 entitymanager。在运行时我得到了 Cannot invoke javax.persistence.EntityManager 并最后显示 because "this.entityManager"is null.

那么谁能指导我解决这个问题或请引用任何文档以供引用?

最佳答案

根据我之前的回答进行编辑,在查看您的代码后,下面是您当前正在做的事情:

  1. 您使用 Configuration 注释创建了 PersistenceConfig.java。此类是空的,看起来您在创建和定义 bean 后对其进行了注释。

  2. Spring 实际上正在检查 PersistenceConfig.java 以查找配置,而不是转到您的 xml。

  3. 将您的 xml 配置移至 src/main/resources 并为支持最佳实践将其重命名为 persistence.xml

  4. 现在,您必须告诉 spring 从 persistence.xml 中读取您的配置,而不是查看其他任何地方。注释掉 PersistenceConfig.java 中的 Configuration 注释并在您的主类中使用以下注释:

:

@SpringBootApplication
@ImportResource({ "classpath:persistence.xml" })
public class SpringMvcHibernateRestApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMvcHibernateRestApiApplication.class, args);
    }
}
  1. 此外,我建议使用 org.springframework.orm.hibernate5.LocalSessionFactoryBean 而不是 org.springframework.orm.hibernate4.LocalSessionFactoryBean 因为它将与您最新的 spring 和 jpa 版本内联。 使用此工具后,您将能够看到 entitymanager 已正确创建。

编辑:根据 OP 的评论,他们的机器不需要第 5 点。

关于java.lang.NullPointerException : Cannot invoke "javax. persistence.EntityManager error in Spring MVC while pulling data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73051212/

相关文章:

java - 如何将 javaFX 14 应用程序导出为 IntelliJ 中的可执行文件?

java - Spring:如何将配置从应用程序传递到库

java - 如何在 Spring Boot REST API 中启用 JSON/Jackson @RequestBody 的严格验证?

java - hibernate 中没有外键的一对多

java - 使用Java应用程序创建EKS集群

java - 如何使用 Spring Boot 注册辅助 servlet?

java - 对数组进行快速高效的计算

java - 如何在不同数据源上的两个类之间建立关系?

java - Hibernate 不保存对象,即使在日志中没有收到任何错误

java - hibernate 。一对一映射,无需交叉引用