【问题标题】:why EntityManager is null in spring transaction?为什么 EntityManager 在春季事务中为空?
【发布时间】:2018-03-12 10:02:10
【问题描述】:

我在我的 java webapp 项目的服务部分编写了这段代码:

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

当我尝试在不使用 checkUserName 方法的情况下插入新记录时,记录将被正确插入,并且 entityManager 在这种情况下不为空,但是当我想检查重复的用户名时,我得到了 NullPointerException。我检查了代码中的每个对象那可能是空的,最后我明白 entityManager 是空的。为什么在 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>

【问题讨论】:

  • 可能是因为您使用 new 创建了服务实例。但如果没有异常的完整堆栈跟踪和相关代码,就不可能说。
  • 我遇到了类似的问题。在我的例子中,一个方法被标记为 final 并且 EntityManager 在 final 方法中始终为空(但仅在使用 @Transactional 注释时)。

标签: java spring spring-mvc entitymanager spring-transactions


【解决方案1】:

也许您正在实例化 PersonService 调用 new PersonService() ?在这种情况下,Spring 没有执行任何操作,因此字段“entityManager”为空。您必须从您的应用程序上下文中获取一个 bean

applicationContext.getBean(PersonService.class);

或者从测试或控制器调用它

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

     @Autowired
     private PersonService personService;

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

【讨论】:

  • 你说得对,我在控制器中为 personService 使用了 Autowired 并在其中使用了 insert 方法,因此它可以正常工作,但我在另一个类中使用了 checkUserName 方法并创建了一个新的 personService 实例,从而导致了 nullPointerException。
  • 我不知道您在哪里使用 checkUserName 但您可以创建一个用@Component 标记的助手或实用程序类,然后在您希望的范围内使用它。另一种选择是通过构造函数使用 IoC(现在推荐):baeldung.com/constructor-injection-in-spring
  • 类似的发布是因为我用 new 关键字对实例服务感到疯狂,这就是 entitymananger 为空的原因。
猜你喜欢
  • 1970-01-01
  • 2013-09-21
  • 2011-04-22
  • 2016-09-13
  • 2021-06-10
  • 2013-08-12
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
相关资源
最近更新 更多