2013-04-03 29 views
0

設置:創建的實體對象後,所有的實例變量是由以下JPA實體給出的Eclipse鏈接

@Entity(name = "MyEntity") 
public class MyEntity { 

    @Id 
    protected String id = null; 

    protected String name = null; 

    protected String adress = null; 

    @Transient 
    protected User user = new User(name, adress); 

    // Required by JPA 
    protected MyEntity() { 
    } 

    public MyEntity(String id, String name, String adress) { 
    // assign instance variables 
    } 

    public String getUser() { 
     return user.toString(); 
    } 

    ... 

} 

當的getUser()將在由Eclipse的鏈接創建myEntity所調用所需的字符串將不予退還。問題是用戶在MyEntity的實例變量被Eclipse Link設置之前被實例化。換句話說,用戶是使用name = null和adress = null創建的。

如何確保在Eclipse Link設置了所有實例變量後創建用戶?

回答

0

可以使用@PostLoad annotation這樣的:

@PostLoad 
private initUser(){ 
     user = new User(name, adress); 
    } 

的方法將被執行,一旦您的實體全負荷並且它的字段設置。

+0

它在Eclipse Link中工作嗎? – user1056903

+0

@ user1056903它是在JPA標準中,所以是的。 – kostja

+0

我已將註釋添加到方法中。但奇怪的是,只有在我重新啓動完整的應用程序後,方法纔會在實體檢索時執行。有人知道這個原因嗎? – user1056903

相關問題