2016-02-02 100 views
0

我後面的教程:http://www.codejava.net/frameworks/hibernate/hibernate-one-to-one-mapping-with-foreign-key-annotations-exampleJPA OneToOne不工作

我有以下代碼:

@Entity 
@Table(name = DomainConstant.TABLE_USER) 
public class User{ 

    @Id 
    @Column(name = DomainConstant.DOMAIN_USER_ID) 
    @GeneratedValue 
    private Long userId; 

    private UserActivationCode userActivationCode; 

    ///////////////////// CONSTRUCTOR.... 
    /// STANDARD GET AND SET.... 


    @OneToOne(cascade = CascadeType.ALL) 
    @JoinColumn(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID) 
    public UserActivationCode getUserActivationCode() { 
     return userActivationCode; 
    } 
} 

@Entity 
@Table(name = DomainConstant.TABLE_USER_ACTIVATON_LINK) 
public class UserActivationCode { 

    @Id 
    @Column(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID) 
    @GeneratedValue 
    private Long userActivationCodeId; 

    @Column(name = DomainConstant.DOMAIN_ACTIVATION_DATE) 
    @Temporal(javax.persistence.TemporalType.DATE) 
    private Date date; 

    @Column(name = DomainConstant.DOMAIN_ACTIVATION_CODE) 
    private String code; 

    ///////////////////// CONSTRUCTOR.... 
    /// STANDARD GET AND SET.... 

} 

當我保存User對象時,它不會使記錄在UserActivationCode,爲什麼呢?

像這樣:

User newUser = new User(); 
newUser.setUserActivationCode(new UserActivationCode("this is example")); 
userDao.save(newUser); 

我只記錄在用戶表。

你能告訴我爲什麼嗎?

回答

1

你的問題是你混合訪問類型。在User實體中,你已經在一個字段上指定@Id(private Long userId),而你已經在一個屬性上定義了連接映射(getter爲UserActivationCode)。如果您在該字段上指定了連接映射,它應該按原樣工作。

@Entity 
@Table(name = DomainConstant.TABLE_USER) 
public class User{ 

    @Id 
    @Column(name = DomainConstant.DOMAIN_USER_ID) 
    @GeneratedValue 
    private Long userId; 

    @OneToOne(cascade = CascadeType.ALL) 
    @JoinColumn(name = DomainConstant.DOMAIN_ACTIVATION_LINK_ID) 
    private UserActivationCode userActivationCode; 

    ///////////////////// CONSTRUCTOR.... 
    /// STANDARD GET AND SET.... 


    public UserActivationCode getUserActivationCode() { 
     return userActivationCode; 
    } 
} 

有關訪問和訪問類型的詳細信息,請參閱Access, Java EE 7