使用JPA进行一对一映射,插入数据时会抛出异常

时间:2014-02-06 05:04:17

标签: java hibernate jpa one-to-one

我正在使用JSP进行一对一的关系。我理解One To One意味着,一个对象只与一个对象相关联。我创建了两个表,其中包含一对一的关系。表POJO类如下所示。

ParentTable:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private int num;

//bi-directional one-to-one association to Childtable
@OneToOne(mappedBy="parenttable")
private Childtable childtable;

ChildTable:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private String email;

private String name;

//bi-directional one-to-one association to Parenttable
@OneToOne
@JoinColumn(name="id")
private Parenttable parenttable;

创建具有One To One关系的表时是否有任何错误。如果不是我试图将数据插入table.Hhile插入数据它抛出异常。

Insert.java

 public class Insert {
    public static void main(String[] args) {
 Parenttable parenttable = new Parenttable();

 Childtable childtable=new Childtable();

 parenttable.setNum(123);
 childtable.setName("prabha");
 childtable.setEmail("prabha@gmail.com");
 childtable.setParenttable(parenttable); 
 EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("jpaCRUDApp");
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction entr = em.getTransaction();
        entr.begin();
        em.persist(childtable);
        entr.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        em.close();
    }
    }
}

例外是:

 Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
 Exception Description: Deployment of PersistenceUnit [jpaCRUDApp] failed. Close all factories for this PersistenceUnit.
 Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services -    2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.IntegrityException

描述符例外:

 Exception [EclipseLink-48] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DescriptorException
 Exception Description: Multiple writable mappings exist for the field [CHILDTABLE.ID].  Only one may be defined as writable, all others must be specified read-only.
 Mapping: org.eclipse.persistence.mappings.OneToOneMapping[parenttable]
 Descriptor: RelationalDescriptor(com.demo1.OneToOne.Childtable --> [DatabaseTable(CHILDTABLE)])    

1 个答案:

答案 0 :(得分:1)

在父表中编辑

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private int num;

//bi-directional one-to-one association to Childtable
@OneToOne(fetch = FetchType.LAZY, mappedBy = "parenttable", cascade = CascadeType.ALL)
private Childtable childtable;

在子表中编辑

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private String email;

private String name;

//bi-directional one-to-one association to Parenttable

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Parenttable parenttable;