我在DAO类的JPA Java中使用自动生成器生成ID。 由于数据库架构愚蠢,我需要生成主键并将相同的ID插入同一表的两列中
@Id
@GeneratedValue(generator = DataConstants.ABC)
@Column(name = "SYS_ID")
private Long Sysid;
@Column(name = "SYS_NUM")
private Long sysNum;
现在我有了上面的DAO类,它可以正常工作,并在SYS_ID列中插入自动生成的主键。
解决此问题的一种方法是插入数据并获取sysid,然后在其上运行Update,这对我来说似乎不可行。
任何帮助将不胜感激
答案 0 :(得分:1)
我最近遇到了类似的问题,最终提出了以下解决方案:我使用休眠,泛滥,龙目岛来描述我的实体:
Master.java
@Entity
@AllArgsConstructor
@NoArgsConstructor
@RegisterForReflection
@Table(name = "MASTER")
@FieldDefaults(level = AccessLevel.PUBLIC)
public class Master extends PanacheEntityBase {
@Id
@Column(name = "MASTERID", nullable = false)
Long masterId;
@Column(name = "DETAILID", nullable = false)
Long detailId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "master", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
Set<Detail> details = new HashSet<>(0);
@Column(name = "DATECREATED", nullable = false)
Date dateCreated;
public static Master createMasterWithLoadId() {
Query nativeQuery = Panache.getEntityManager().createNativeQuery("select MASTER_SEQ.nextval from dual");
Master master = new Master();
master.masterId = id;
master.detailId = id;
return master;
}
@PrePersist
public void prePersist() {
if (dateCreated == null) {
dateCreated = clearTime(Calendar.getInstance()).getTime();
}
}
private Calendar clearTime(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
}
Detail.java
@Entity
@NoArgsConstructor
@AllArgsConstructor
@RegisterForReflection
@IdClass(BatchContent.ContentId.class)
@Table(name = "DETAIL")
@FieldDefaults(level = AccessLevel.PUBLIC)
public class Detail extends PanacheEntityBase {
@Id
@ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinColumn(name = "detailId", nullable = false)
Master master;
@Id
@Column(name = "one")
Long one;
@Id
@Column(name = "two")
Long two;
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@RegisterForReflection
@FieldDefaults(level = AccessLevel.PRIVATE)
static class DetailId implements Serializable {
Master master;
Long one;
Long two;
}
}
使用:
Master master = Master.createMasterWithLoadId();
for (RequestDetail rDet : rDetails) {
master.details.add(new Detail(master, rDet.getOne(), rDet.getTwo()));
}
master.persist();