Hibernate在访问线程中的对象时无法初始化proxy-no-Session



如何设置Thread类以访问父类可以访问的会话?

当前父类使用的是具有多个对象的SetSomeObject。这些对象需要由正在扩展ThreadDeviceRunner使用。

这个应用程序使用的是Spring Boot/Spring Data JPA/Hibernate。

更新

是否可以像@Controller那样@Autowirerepository?如下所示的@Autowired repository返回null。

设置@Transactional允许我处理SomeObject的对象,但我无法获得RepositoryAutowire,因此我可以创建/保存?

谢谢

代码DeviceRunner扩展线程

@Transactional(propagation=Propagation.REQUIRED)
public class DeviceRunner extends Thread {
    @Autowired
    public TestRunRepository repository;
    public SomeObject object;        
    private .....
    public DeviceRunner(args.... ) {
        // set private variables
    }
    public void run() {
        // do stuff
    }
    synchronized ....
}

编码SomeObject

@Data
@Entity
@Table(name = "test_run")
public class SomeObject {
  @ManyToMany(fetch = FetchType.LAZY)
  private Set<OtherObjects> otherObjects;
}

TestRunRepository

@Repository
@Transactional
public interface TestRunRepository extends PagingAndSortingRepository<TestRun, Long> {
}

创建线程的Rest控制器

@Transactional(propagation=Propagation.REQUIRED)
 @RestController
public class HomeController {
 @Autowired
 public TestRunRepository repository;
  ....
  @Transactional
  private void runTestRunOnDevice(TestRun testRun) {

      DeviceRunner deviceRunner = new DeviceRunner(testRun);
      deviceRunner.start();
      while (deviceRunner.isAlive());
  }
}

您可以使用带有传播的事务作为Required,这是默认的。@Transactional(Propagation.REQUIRED)

我会将@Autowired EntityManagerSession添加到您的Repository类中。它有效。Spring Data注入一个代理,该代理根据事务上下文(即,根据调用它的当前执行线程)生成实际的EntityManager/Session

相关内容

最新更新