java.lang.NullPointerException 使用 EntityManager 的 persist() func (Spring 4 ORM)

Posted

技术标签:

【中文标题】java.lang.NullPointerException 使用 EntityManager 的 persist() func (Spring 4 ORM)【英文标题】:java.lang.NullPointerException when using EntityManager's persist() func (Spring 4 ORM) 【发布时间】:2016-05-20 16:20:33 【问题描述】:

我已经解决了许多类似的问题,但仍然陷入了死胡同。

我创建了模型、dao 和服务类。我正在编写我的 JUnit 测试套件,但是当我尝试测试我的持久功能时,我得到一个 java.lang.NullPointerException。我确实尝试在我的 IDE 中设置一些断点并进行调试,但令人费解的是为什么会发生这种情况。

下面是我的模型、dao 和服务的代码以及我的 spring.xml 文件。

模型(为简洁起见,我避开了构造函数和其他字段)

@Entity
public class Request implements Serializable 

    @Id
    private Integer restRequestId;

    private Timestamp restRequestTimestamp;

    private String restRequestParameters;


@Component
public class RequestDAO 

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Request request) 
        entityManager.persist(request);
    

    public void update(Request request) 
        entityManager.getTransaction().begin();
        entityManager.merge(request);
        entityManager.getTransaction().commit();
    

    public Object findById(Serializable id) 
        Request request = entityManager.find(Request.class, id);
        if (request == null) 
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        
        return request;
    

    public void delete(Request request) 
        entityManager.getTransaction().begin();
        entityManager.remove(request);
        entityManager.getTransaction().commit();
    

    public void deleteById(Serializable id) 
        Request request = entityManager.find(Request.class, id);
        if (request == null) 
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
         else if (request != null) 
            entityManager.getTransaction().begin();
            entityManager.remove(request);
            entityManager.getTransaction().commit();
        
    

    public List<Request> findAll() 
        Query query = entityManager.createQuery("SELECT e from Request e");
        List<Request> requests = query.getResultList();
        return requests;
    

    public void deleteAll() 
        List<Request> requests = findAll();
        for (Request request : requests) 
            delete(request);
        
    



请求服务

@Component
public class RequestService 

    @Autowired
    private RequestDAO requestDAO;

    @Transactional
    public void add(Request request) 
        requestDAO.persist(request);
    

    @Transactional
    public void update(Request request) 
        requestDAO.update(request);
    

    @Transactional
    public Object findById(Serializable id) 
        return requestDAO.findById(id);
    

    @Transactional
    public void delete(Request request) 
        requestDAO.delete(request);
    

    @Transactional
    public void deleteById(Request request) 
        requestDAO.delete(request);
    

    @Transactional
    public void deleteAll() 
        requestDAO.deleteAll();
    

    @Transactional
    public void addAll(Collection<Request> requestCollection) 
        for (Request request : requestCollection) 
            requestDAO.persist(request);
        
    

    @Transactional(readOnly = true)
    public List<Request> findAll() 
        return requestDAO.findAll();
    


spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">


    <context:component-scan base-package="com.company"/>
    <mvc:annotation-driven/>
    <context:annotation-config/>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem://requestDb"/>
        <property name="username" value="user"/>
        <property name="password" value="pass"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="com.company"
          p:dataSource-ref="dataSource">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

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


</beans>

JUnit 测试类

public class RequestServiceTest 

    @Autowired
    RequestDAO requestDAO;


    @Before
    public void setUp() throws Exception 
    

    @After
    public void tearDown() throws Exception 

    

    @Test
    public void add() throws Exception 
        RequestService requestService = new RequestService();
        Request requestObject = new Request();
        requestObject.setRestRequestId(1);
        requestObject.setRestRequestParameters("hello");
        requestService.add(requestObject);
        Request requestResponseFromDatabase = (Request) requestService.findById(1);
        assertEquals("hello", requestResponseFromDatabase.getRestRequestParameters());
    

【问题讨论】:

【参考方案1】:

您的单元测试如何知道应该由 Spring 驱动?为了在 JUnit 测试中使用 Spring,您应该使用 Spring 运行(使用 @RunWith(SpringJUnit4ClassRunner.class) 注释并提供一些额外的配置)。

否则,JUnit 甚至不会处理 @Autowire

您可以在此here 上阅读更多信息。

【讨论】:

不敢相信我忘记了。这解决了我的问题,非常感谢您提供更多信息!

以上是关于java.lang.NullPointerException 使用 EntityManager 的 persist() func (Spring 4 ORM)的主要内容,如果未能解决你的问题,请参考以下文章

亲測,Eclipse报&quot;An error has occurred,See error log for more details. java.lang.NullPointerExce

来自 LayerDrawable 的异常

Microsoft Access 和 Java JDBC-ODBC 错误

如何使用其id获取单个SQLite行数据?