I Generate id with autogenerator in JPA java in DAO class. Because of the silly database architecture I need to generate the primary key and insert same id into two columns in same table
@Id
@GeneratedValue(generator = DataConstants.ABC)
@Column(name = "SYS_ID")
private Long Sysid;
@Column(name = "SYS_NUM")
private Long sysNum;
Right now I have the DAO class as above which works fine and insert auto generated primary key in SYS_ID column.
One way to solve this is insert the data and get the sysid and then run Update on it which doesn;t seem feasible to me.
Any help would be appreciated
I recently encountered a similar problem and eventually came up with the following solution: I use hibernate, panache, lombok for discription my entities:
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;
}
}
use:
Master master = Master.createMasterWithLoadId();
for (RequestDetail rDet : rDetails) {
master.details.add(new Detail(master, rDet.getOne(), rDet.getTwo()));
}
master.persist();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.