简体   繁体   English

为什么在春季交易中EntityManager为null?

[英]why EntityManager is null in spring transaction?

I wrote this code in the Service part of my java webapp project: 我在Java webapp项目的Service部分中编写了以下代码:

@Service
@Transactional
public class PersonService extends BaseService {
    @PersistenceContext
    private EntityManager entityManager;

    public void insert(Person person) {
        entityManager.persist(person);
    }

    public boolean checkUserName(String userName) {
        try {

                System.out.println("Entity null ni");
                Person person = (Person) entityManager.createQuery("select entity from person entity where entity.USER_NAME=:userName")
                        .setParameter("userName", userName)
                        .getSingleResult();
                if (person == null)
                    return true;
                else {
                    return false;
                }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

When I tried to insert a new record without using the checkUserName method, the record would be inserted correctly and entityManager was not null in this condition but when I wanted to check repetitive userName I got NullPointerException.I checked every Object in my code that could be null finally I understand entityManager is null.why entityManager is null in Spring Transaction.this is spring.xml 当我尝试不使用checkUserName方法插入新记录时,该记录将被正确插入并且在这种情况下EntityManager不为空,但是当我想检查重复的userName时,我得到了NullPointerException。我检查了代码中的每个Object最终我理解为null。为什么在Spring Transaction中EntityManager为空。这是spring.xml

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

    <!--SpringMVC-->
    <context:component-scan base-package="Laitec.Doctor"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>

    </bean>
    <!-- SpringTransaction-->
    <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="Laitec.Doctor.model.entity"/><!--ToPackageAddress-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--<prop key="hibernate.hbm2ddl.auto">create-drop</prop>-->
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            </props>
        </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
        <property name="username" value="username"/>
        <property name="password" value="password"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryBean"/>
    </bean>
    <tx:annotation-driven/>
</beans>

Maybe are you instantiating PersonService calling new PersonService() ? 也许您要实例化PersonService调用new PersonService()? In this case Spring is not performing any operation and thus field 'entityManager' is null. 在这种情况下,Spring不执行任何操作,因此字段'entityManager'为null。 You must get a bean from your Application Context 您必须从应用程序上下文中获取一个bean

applicationContext.getBean(PersonService.class);

Or invoking it from a test or a controller 或从测试或控制器中调用它

@RestController
@GetMapping("people")
public class PersonController() {

     @Autowired
     private PersonService personService;

     @PostMapping
     public void home(@RequestBody Person person) {
         personService.insert(person);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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