【发布时间】:2019-09-23 06:07:04
【问题描述】:
我正在尝试在 JPA 中映射下图中描述的一对多表关系:
可以看出,"activity_property" 表使用复合主键,(id,name) 和列"id" 是表"activity" 中列"id" 的外键。
我当前的实体是这样映射的(为了清楚起见,省略了一些辅助方法):
Activity.java
@Entity
@Getter
@Setter
public class Activity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "act_id_generator")
@SequenceGenerator(name = "act_id_generator", sequenceName = "activity_id_seq", allocationSize = 1, initialValue = 1)
private Integer id;
private String name;
@OneToMany(mappedBy = "id.activityId", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ActivityProperty> properties;
}
ActivityProperty.java
@Entity
@Getter
@Setter
@Table(name = "activity_property")
public class ActivityProperty {
@EmbeddedId
private ActivityPropertyId id;
private String value;
@Enumerated(EnumType.STRING)
private PropertyType type;
}
ActivityPropertyId.java
@Embeddable
@Getter
@Setter
@ToString
public class ActivityPropertyId implements Serializable {
@Column(name = "id")
private Integer activityId;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivityPropertyId that = (ActivityPropertyId) o;
return activityId.equals(that.activityId) &&
name.equals(that.name);
}
@Override
public int hashCode() {
return Objects.hash(activityId, name);
}
}
当我尝试以这种方式保持活动时:
Activity activity = createActivity("Activity_1");
activity.addProperty(ActivityProperty.from("Prop1", "value1", PropertyType.PARAMETER));
activityDAO.persist(activity);
我可以在 Hibernate 中看到以下痕迹:
Hibernate: call next value for activity_id_seq
Hibernate: insert into activity (name, id) values (?, ?)
Hibernate: insert into activity_property (type, value, id, name) values (?, ?, ?, ?)
05-05-2019 12:26:29.623 [main] WARN o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions - SQL Error: 23502, SQLState: 23502
05-05-2019 12:26:29.624 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions - NULL not allowed for column "ID"; SQL statement:
insert into activity_property (type, value, id, name) values (?, ?, ?, ?) [23502-199]
Activity 的自动生成 ID 似乎没有在 ActivityProperty 的第二次插入中使用。
我不知道如何正确映射这种关系。我的 JPA 注释中是否缺少任何内容?
【问题讨论】: