我正在使用JSP做一对一的关系。我了解一对一的意思是,一个对象仅与一个对象相关联。我使用一对一关系创建了两个表。表POJO类如下所示。

父表:

@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;


子表:

@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;


创建具有一对一关系的表时是否有任何错误。如果不是,我试图将数据插入表中,而在插入数据时会抛出异常。

插入.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("[email protected]");
 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)])

最佳答案

在父表中编辑

@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;

09-04 09:49