2016-07-27 49 views
1

如何設置我的Thread類以便能夠訪問父類可以訪問的會話?Hibernate無法初始化代理 - 在線程中訪問對象時沒有會話

當前父類正在使用SomeObject其中有多個Set的對象。 DeviceRunner需要使用這些對象,這是擴展Thread

此應用程序使用Spring Boot/Spring Data JPA/Hibernate。

更新

是否有可能@Autowirerepository,我會爲一個@Controller?如下所示的@Autowiredrepository返回null。

設置@Transactional允許我處理SomeObject的對象,但我無法獲得RepositoryAutowire,因此我可以創建/保存?

謝謝

代碼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()); 
    } 
} 
+0

您是否需要從線程修改SomeObject或者只是讀取它? – takteek

+0

你確定你不會在調用方法中缺少@Transactional(readOnly = true)嗎? – Sarief

回答

1

您可以將使用傳播的事務處理爲默認值的Required。 @Transactional(Propagation.REQUIRED)

+0

當設置Transactional(Propogation.REQUIRED)時是否需要完成這看起來工作允許我從SomeObject訪問對象,但是存儲庫不能自動裝配,所以我無法在線程中訪問它們。我上面更新了我的代碼 – ALM

1

我想補充@Autowired的EntityManager會議到存儲庫類。有用。 Spring Data根據事務上下文(即取決於調用它的當前執行的線程)注入一個代理,該代理產生實際的EntityManager/Session

+0

如上所示設置Autowired不允許將存儲庫連線到該類。我必須以不同的方式做到這一點嗎?目前我將它作爲構造函數的一部分傳入,但希望自動裝配它。 – ALM

+0

要麼像'@Autowired Repository(EntityManager em)'這樣的構造函數或像'@Autowired void setEntityManager(EntityManager em)'或字段(從可測試性的角度來看不太推薦)那樣設置註解。所有3種方式應該工作。 – Alexander

相關問題