我正在尝试模拟一对一的关系。当我尝试
在连接列属性中添加 nullable = false 时,我得到一个 SQLIntegrityContraintViolationException 说地址的 ID 为空。我期待这是因为,我在 id 中使用的自动生成的值是在提交时生成的。(我对吗 ?) ...
但是,当我在地址构造函数中进行修改时,通过在那里设置一个 id 然后尝试持久化..我得到了同样的异常。我不懂为什么。
但是,如果我删除 nullable = false,我可以正常执行它。请解释我哪里出错了。
这是我的实现.. 为简单起见,省略了 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();
}
}
我哪里错了?