JPA joinColumn错误

时间:2012-06-08 10:04:58

标签: java java-ee jpa

我试图模拟一对一的关系。当我尝试添加nullable = false时,
在join column属性中,我得到一个SQLIntegrityContraintViolationException,表示地址ID为null。我期待这个,因为我在id中使用的自动生成的值是在提交时生成的。 (我是对的吗?)......

但是,当我在地址构造函数中进行修改时,通过在那里设置id然后尝试继续...我得到了相同的异常。我不明白为什么。

但是,如果我删除了nullable = false,我可以正常执行它。请解释我哪里出错了。

这是我的实现..为了简单起见,省略了Getters和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();
    }
}

我哪里错了?

1 个答案:

答案 0 :(得分:0)

您应该将持久操作从客户级地址级联到地址。 您正在保存客户,但该地址尚未生成ID,因为它已生成