如何設置我的Thread
類以便能夠訪問父類可以訪問的會話?Hibernate無法初始化代理 - 在線程中訪問對象時沒有會話
當前父類正在使用SomeObject
其中有多個Set
的對象。 DeviceRunner
需要使用這些對象,這是擴展Thread
。
此應用程序使用Spring Boot/Spring Data JPA/Hibernate。
更新
是否有可能@Autowire
的repository
,我會爲一個@Controller
?如下所示的@Autowired
repository
返回null。
設置@Transactional允許我處理SomeObject的對象,但我無法獲得Repository
到Autowire
,因此我可以創建/保存?
謝謝
代碼DeviceRunner擴展Thread:
@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> {
}
休息控制器,它創建線程
@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());
}
}
您是否需要從線程修改SomeObject或者只是讀取它? – takteek
你確定你不會在調用方法中缺少@Transactional(readOnly = true)嗎? – Sarief