2012-06-08 88 views
0

我想模擬一對一的關係。當我嘗試在連接列屬性中添加nullable = false,
時,我得到一個SQLIntegrityContraintViolationException,表示地址的ID爲空。我期待這樣做,因爲我在id中使用的自動生成的值是在提交時生成的。 (我是正確的?)...JPA joinColumn錯誤

但是,當我在地址構造函數中進行修改時,通過設置一個id然後嘗試持久化..我得到相同的異常。我不懂爲什麼。

然而,如果刪除了可空=假,我可以正常exeucte它。請解釋我出錯的地方。

這裏是我實現.. getter和setter方法簡單,省略。

@Entity 
    public class CustomerEX implements Serializable { 
     private static final long serialVersionUID = 1L; 
     @Id 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     private Long id; 
     private String name; 
     @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST) 
     @JoinColumn(name="address_fk") 
     private AddressEx address; 

    public void setAddress(AddressEx address) { 
    this.address = address; 
    this.address.setCustomer(this); 
} 

     --- 
     ---- 
    } 

and 

     @Entity 
    public class AddressEx implements Serializable { 

     private static final long serialVersionUID = 1L; 
     @Id 
     @GeneratedValue 
     private Long id; 
     private String city; 
     private String country; 
     @OneToOne 
     private CustomerEX customer; 
     } 

,我的主要功能是像...

public class CustomerTest { 

    public static void main(String[] args) { 
     AddressEx addr = new AddressEx(); 
     addr.setCity("Bangalore"); 
     addr.setCountry("India"); 
     System.out.println(addr.getId()+ " is the id of this object"); 
     CustomerEX cust = new CustomerEX(); 
     cust.setName("ravi"); 

     cust.setAddress(addr); 

     EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceAppPU"); 
     EntityManager em = emf.createEntityManager(); 

     EntityTransaction etx = em.getTransaction();     
     etx.begin(); 
     em.persist(cust); 
     etx.commit(); 
    } 
} 

我在哪裏去了?

+0

嘗試在em.persist()後添加em.flush()。 – JMelnik

回答

0

您應該將客戶的持續行爲級聯到地址。 您正在保存客戶,但該地址尚未生成Id,因爲它生成了