【发布时间】:2016-07-27 07:23:04
【问题描述】:
如何设置我的Thread 类以能够访问父类有权访问的会话?
当前父类使用SomeObject,它有多个Set 的对象。扩展Thread 的DeviceRunner 需要使用这些对象。
此应用程序正在使用 Spring Boot/Spring Data JPA/Hibernate。
更新
是否可以像 @Controller 一样 @Autowire repository?如下图@Autowiredrepository返回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 ....
}
编码 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 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());
}
}
【问题讨论】:
-
你需要从线程中修改SomeObject还是直接读取?
-
你确定你没有在调用方法中丢失@Transactional(readOnly = true) 吗?
标签: java spring multithreading hibernate spring-data