相关疑难解决方法(0)

当使用getOne和findOne方法时,Spring Data JPA

我有一个用例,它调用以下内容:

@Override
@Transactional(propagation=Propagation.REQUIRES_NEW)
public UserControl getUserControlById(Integer id){
    return this.userControlRepository.getOne(id);
}
Run Code Online (Sandbox Code Playgroud)

观察@Transactionalhas Propagation.REQUIRES_NEW,存储库使用getOne.当我运行该应用程序时,收到以下错误消息:

Exception in thread "main" org.hibernate.LazyInitializationException: 
could not initialize proxy - no Session
...
Run Code Online (Sandbox Code Playgroud)

但是,如果我改变getOne(id)findOne(id)一切工作正常.

顺便说一下,就在用例调用getUserControlById方法之前,它已经调用了insertUserControl方法

@Override
@Transactional(propagation=Propagation.REQUIRES_NEW)
public UserControl insertUserControl(UserControl userControl) {
    return this.userControlRepository.save(userControl);
}
Run Code Online (Sandbox Code Playgroud)

两种方法都是Propagation.REQUIRES_NEW,因为我正在进行简单的审计控制.

我使用该getOne方法,因为它是在JpaRepository接口中定义的,我的Repository接口从那里扩展,我当然正在使用JPA.

JpaRepository接口扩展自CrudRepository.该findOne(id)方法定义于CrudRepository.

我的问题是:

  1. 为什么失败的getOne(id)方法?
  2. 什么时候应该使用这种getOne(id)方法?

我正在使用其他存储库并且所有使用该getOne(id)方法并且所有工作正常,只有当我使用Propagation.REQUIRES_NEW …

jpa spring-data spring-data-jpa

135
推荐指数
4
解决办法
15万
查看次数

标签 统计

jpa ×1

spring-data ×1

spring-data-jpa ×1