如何设置我的 Thread
类能够访问父类有权访问的 session ?
当前父类正在使用SomeObject
其中有多个Set
的对象。 DeviceRunner
需要使用这些对象正在扩展Thread
。
此应用程序使用 Spring Boot/Spring Data JPA/Hibernate。
更新
有可能@Autowire
repository
就像我想要的 @Controller
? @Autowired
repository
如下所示返回null。
设置 @Transactional 允许我处理 SomeObject 的对象,但我无法获取 Repository
至Autowire
这样我就可以创建/保存?
谢谢
扩展线程的代码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 ....
}
编写一些对象
@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 Controller
@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());
}
}
最佳答案
您可以将事务与传播一起使用,这是默认的。
@Transactional(Propagation.REQUIRED)
关于java - Hibernate 无法初始化代理 - 在线程中访问对象时没有 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38606399/