使用合并方法将ManyToMany存储为额外列

时间:2016-09-06 14:38:53

标签: jpa many-to-many

我有一个实体类,它只是一个带有额外列的ManyToMany,如下所示:

@Entity
@Table(name = "view_templates_device_types")
public class ViewTemplateDeviceTypeEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @ManyToOne
    @JoinColumn(name = "view_template_id")
    private ViewTemplateEntity viewTemplate;

    @Id
    @ManyToOne
    @JoinColumn(name = "device_type_id")
    private DeviceTypeEntity deviceType;

    @Column(name = "priority", nullable = false)
    private int priority;

    public ViewTemplateDeviceTypeEntity() {

    }
    ...
}

我注意到当我创建这种类型的新对象时,将viewTemplate和deviceType设置为db中具有相应数据的值,然后调用entityManager.persist(entity)数据进行存储。但是当我拨打entityManager.merge(entity)而不是persist时,我得到了一个例外:

  

SQL错误:1048,SQLState:23000
  列'view_template_id'不能为null

我认为调用merge会导致数据插入到数据库中,以防它尚未存储。在这里使用merge非常重要(因为级联)。我能做些什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

根据JPA规范,第2.4节 "A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId or IdClass annotation is used to denote a composite primary key. See Sections 11.1.17 and 11.1.22.".

因此,您需要@IdClass@EmbeddedId。其他任何东西都是不可移植的,容易出错。我对任何不会因此而发出警告的JPA提供商感到非常惊讶。