如何设置Thread
类以访问父类可以访问的会话?
当前父类使用的是具有多个对象的Set
的SomeObject
。这些对象需要由正在扩展Thread
的DeviceRunner
使用。
这个应用程序使用的是Spring Boot/Spring Data JPA/Hibernate。
更新
是否可以像@Controller
那样@Autowire
和repository
?如下所示的@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 ....
}
编码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 EntityManager或Session添加到您的Repository类中。它有效。Spring Data注入一个代理,该代理根据事务上下文(即,根据调用它的当前执行线程)生成实际的EntityManager/Session。