jpa-2.0 - JPA,带有外键的复合键+持久化oneToMany

标签 jpa-2.0 eclipselink java-ee-6

我正在尝试使用 JPA 做一些在项目中需要大量使用的事情,但我陷入了困境。

我有 2 个实体 + 一种“胶水”实体,我称之为它们

  • A 类
  • B类
  • 胶水

我想添加一个新的 ClassA,并在其列表中设置新的胶水,ClassB 已经存在。

这会做类似的事情:

ClassA 1 | Glue 1 1 | ClassB 1
ClassA 1 | Glue 1 2 | ClassB 2
ClassA 1 | Glue 1 3 | ClassB 3
ClassA 1 | Glue 1 4 | ClassB 4

So as said ClassA and all Glues are to be inserted, ClassA has a List with the new Glues to be inserted.

Here they are :

@Entity
public class ClassA implements Serializable {

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

    (...)

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "classA")
    private List<Glue> glueList;

    (...)
}

@Entity
public class ClassB implements Serializable {

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

    (...)
}

@Entity
public class Glue implements Serializable {

    @EmbeddedId
    protected GluePK gluePK;

    @JoinColumn(name = "id_class_a", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private ClassA classA;

    @JoinColumn(name = "id_class_b", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private ClassB classB;

    (...)
}

@Embeddable
public class GluePK implements Serializable {

    @Basic(optional = false)
    @NotNull
    @Column(name = "id_class_a", nullable = false)
    private int idClassA;

    @Basic(optional = false)
    @NotNull
    @Column(name = "id_class_b", nullable = false)
    private int idClassB;

    (...)
}

当我尝试坚持我的 ClassA 时,我得到了类似的信息:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 无法添加或更新子行:外键约束失败 (bdd.glue, CONSTRAINT constraint_name FOREIGN KEY (id_class_a) code>) 引用 ClassA (id) 删除时无操作 更新时无操作)

我知道他提示 Glues 没有 ClassA 的引用集,但我希望他在坚持 ClassA 时填写它。

这可以实现吗? 如果不是,最好的方法是什么?

我想继续使用 JPA,而不需要任何特定的供应商技巧(我正在使用 eclipselink),但如果某个供应商可以轻松做到这一点,我会继续使用。

谢谢!

最佳答案

我会删除 EmbeddedId,改用 IdClass,然后将 @Id 添加到 @ManyToOne 映射中。

看, http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0

或者甚至可以给 Glue 一个自己的 id。

您还可以从 @ManyToOne 中删除 insertable = false、updatable = false 并将它们移动到 EmbeddedId。

关于jpa-2.0 - JPA,带有外键的复合键+持久化oneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310225/

相关文章:

spring - Tomcat 7.0.10 是否符合 Java EE 6? javax.inject 问题

java - 如何使用 JPA 2 连接到多个数据源?

java - JPA 2.0 CriteriaQuery,其类型为类或任何子类的谓词

java - 具有共享 key (MapsId)和延迟加载问题的 OneToOne

hibernate - 自定义类似谓词来处理自定义用户定义类型(Hibernate UserType)

jboss - EclipseLink-Moxy 无法在实例化 JAXB 上下文时加载自定义 DomHandler 类

java - JSF 2.0 验证码的工作原理

java - 以编程方式访问 JPA <persistence-unit-metadata>

JPA 和 eclipselink - 覆盖 FetchType.Eager

java - NetBeans:在 Web 模块的 EJB 模块中使用 EJB