简体   繁体   中英

java.lang.NullPointerException when using EntityManager's persist() func (Spring 4 ORM)

I have gone through numerous questions similar to this, but still stuck at a dead end.

I created my model, dao, and service classes. I am writing my JUnit test suite, however when I try to test my persisting functionality, I get a java.lang.NullPointerException. I did try to set up a few breakpoints and debug within my IDE but it is puzzling as to why this is happening.

My code for my model, dao, and service are below along with my spring.xml file.

Model (I avoided the constructor and other fields for brevity)

@Entity
public class Request implements Serializable {

    @Id
    private Integer restRequestId;

    private Timestamp restRequestTimestamp;

    private String restRequestParameters;
}

Dao

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

}

RequestService

@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 test class

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());
    }
}

How does your unit test know that should be driven by Spring? In order to use Spring in JUnit tests, you should run with Spring (use the @RunWith(SpringJUnit4ClassRunner.class) annotation and provide some additional configuration).

Otherwise, JUnit doesn't even process the @Autowire .

You can read more on this here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM