【问题标题】:Persist @OneToMany List坚持@OneToMany 列表
【发布时间】:2015-04-06 20:34:22
【问题描述】:

我正在尝试坚持以下内容:

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

在我的父亲DAO中

@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)”时,只有父亲保存在数据库中,而不是儿子(列表)。

现在出错:

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,这是导致错误的原因。

谢谢

【问题讨论】:

  • 我还不能解决... :(

标签: java hibernate postgresql jpa


【解决方案1】:

尝试以下更改。

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

【讨论】:

  • 可以粘贴测试用例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多