坚持@OneToMany列表

时间:2015-04-06 20:34:23

标签: java hibernate postgresql jpa

我试图坚持以下内容:

@Entity
@Table(name="tb_father")
public class Father implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "tb_father_id_seq", sequenceName = "tb_father_id_seq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "tb_father_id_seq")
@Column(name = "id", nullable = false)
private Integer id;

@OneToMany(fetch = FetchType.LAZY, mappedBy="father", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Son> sons;

... Gets and Sets

}


@Entity
@Table(name="tb_son")
public class Son  implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "tb_son_id_seq", sequenceName = "tb_son_id_seq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "tb_son_id_seq")
@Column(name = "id", nullable = false)
private Integer id;

@Inject
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="father", referencedColumnName="id")
private Father father;


... Gets and Sets

}

示例:

Father father = new Father();
Son son = new Son();
...
father.getSons().add(son);

在我的FatherDAO

@Stateless
public class FatherDAO {

    @PersistenceContext(unitName = "test")
    private EntityManager em;

    @TransactionAttribute(TransactionAttributeType.MANDATORY)
    public void persistFatherSons(Father father) throws ApplicationException {
        try {
            em.persist(father);
        } catch(Exception e) {
        ...
        }
    }

...

}

表:

CREATE TABLE tb_father
(
    id integer NOT NULL,
    CONSTRAINT tb_father_pkey PRIMARY KEY (id),
)

CREATE TABLE tb_son
(
   id integer NOT NULL,
   father integer,
   CONSTRAINT tb_son_pkey PRIMARY KEY (id),
   CONSTRAINT fk41b1efcfa0ebdd8c FOREIGN KEY (father)
       REFERENCES tb_father (id) MATCH SIMPLE
)

运行“em.persist(father)”时,只有父亲保存在数据库中,而不是Sons(List)。

现在出错:

08:00:21,123 WARN  [com.arjuna.ats.arjuna] (http--10.36.1.49-8180-1) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffff7f000101:-81b794d:5523b2cf:61, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization@6bb7796b >: javax.persistence.PersistenceException: error during managed flush
at  org.hibernate.ejb.AbstractEntityManagerImpl$CallbackExceptionMapperImpl.mapManagedFlushFailure(AbstractEntityManagerImpl.java:1486) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
...

准备好了!两个实体ai是我创建的示例,用于演示此处发生的问题。示例中缺少的是 Float 字段。此字段为 @Size ,这导致错误。

Thankssss

1 个答案:

答案 0 :(得分:0)

尝试以下更改。

@Inject
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="father")
private Father father;