I have 2 entities:
Master:
@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "seq")
private Integer seq;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "seq", referencedColumnName = "seq")
private SubMaster subMaster;
...................
}
Sub Master:
@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {
@Id
@Column(name = "seq")
private Integer seq;
private String subName;
...................
}
When, I am trying to persist Master
entity by setting the SubMaster
entity, I am getting following exception:
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save(): SubMaster
Whereas, I am expecting that Hibernate it will automatically persist child entity whenever parent entity is persisted.
也为SubMaster添加@GeneratedValue(strategy = IDENTITY),似乎是SubMaster的ID生成了异常
First of all you inverted the owner of the association as i believe subMaster should have the @JoinColumn annotation.
now for the solution
Depends on JPA version:
-2.0 you can define @Id
annotation on relation annotation so you could have something like
@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "seq")
private Integer seq;
@OneToOne(mappedBy = "master", cascade = CascadeType.ALL)
private SubMaster subMaster;
}
@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {
@Id
@JoinColumn(name = "seq", referencedColumnName = "seq")
@OneToOne
private Master master;
private String subName;
}
where you tell your child entity to take the id of the parent
master.setSubMaster(subMaster);
subMaster.setMaster(master)
-1.0 you are pretty much stuck as you are forced to place @Id
on a basic annotation so you need to have an id and a relation column separated, the problem is that with @GeneratedValue
you are forced to first save the parent and then manually set the id to the child before saving
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.