【问题标题】:Embeddable PK Object not populating after persist and flush持久化和刷新后不填充可嵌入 PK 对象
【发布时间】:2011-09-23 16:53:19
【问题描述】:

我有一个嵌入式 PK 对象,它在持久化并刷新到数据库后不会填充 id 字段。 ID 是数据库中的自动增量字段。

现在通常,我会尝试刷新,但它会引发以下错误:

“实体不再存在于数据库中:entity.Customers[ customersPK=entity.CustomersPK[ id=0, classesId=36 ] ]。”

public class Customers implements Serializable {

    @EmbeddedId
    protected CustomersPK customersPK;
    ...
}

@Embeddable
public class CustomersPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "id")
    private int id;

    @Basic(optional = false)
    @NotNull
    @Column(name = "classes_id")
    private int classesId;
    .....
 }

这是调用的代码

Classes cl = em.find(Classes.class, classId);

CustomersPK custPK = new CustomersPK();
custPK.setClassesId(cl.getId());
Customers cust = new Customers(custPK);

em.persist(cust);
em.flush(); 


// The problem is right here where id always equals 0
int id = cust.getCustomerspk().getId();

感谢您的帮助。

【问题讨论】:

    标签: java jakarta-ee jpa persistence


    【解决方案1】:

    为什么id不为0,你从来没有设置过?

    如果是生成的id,需要用@GeneratedValue注解,否则需要设置值。

    【讨论】:

    • 谢谢,还在学习 JPA。没有必要在我的其他表中使用 @GeneratedValue 表示法,因为它们没有 PK 对象并且 flush() 获取了 ID。所以,这对我来说并不完全明显。再次感谢。
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多