使用合并方法存储带有额外列的 ManyToMany
Storing ManyToMany with extra column using merge method
我有一个实体 class,它只是一个带有额外列的 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 设置为在数据库中具有相应数据的值,然后我调用 entityManager.persist(entity)
存储数据。但是当我调用 entityManager.merge(entity)
而不是 persist
时,我得到一个异常:
SQL Error: 1048, SQLState: 23000
Column 'view_template_id' cannot be null
我认为调用合并应该将数据插入数据库,以防尚未存储。在这里使用 merge
对我来说非常重要(因为级联)。我该怎么做才能让它发挥作用?
根据 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 提供者感到非常惊讶。
我有一个实体 class,它只是一个带有额外列的 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 设置为在数据库中具有相应数据的值,然后我调用 entityManager.persist(entity)
存储数据。但是当我调用 entityManager.merge(entity)
而不是 persist
时,我得到一个异常:
SQL Error: 1048, SQLState: 23000
Column 'view_template_id' cannot be null
我认为调用合并应该将数据插入数据库,以防尚未存储。在这里使用 merge
对我来说非常重要(因为级联)。我该怎么做才能让它发挥作用?
根据 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 提供者感到非常惊讶。