I have 2 entities that use the same sequence as the primary key, how do I map? Example:
@Entity
@Table("employeT")
public class Employe(){
@SequenceGenerator(name = "generator_id", sequenceName = "seq_id")
@GeneratedValue(generator = "generator_id")
@colunm(name = "id")
private Integer id;
@colunm(name = "nameEmp")
private String name;
@JoinColumn(name = "id")
private Computer computer;
}
@Entity
@Table("computerT")
public class Computer(){
@SequenceGenerator(name = "generator_id", sequenceName = "seq_id")
@GeneratedValue(generator = "generator_id")
@colunm(name = "id")
private Integer id;
@colunm(name="name_computer")
private String nameComputer;
}
I need save employe and computer with same id, generated by Employe save.
There are three things to do with your code to work the way to want to.
So it would look something like this :
@Entity
@Table("employeT")
public class Employe(){
@Id
private Integer id;
@Colunm(name = "nameEmp")
private String name;
@OneToOne
@JoinColumn(name = "computer_id")
@MapsId
private Computer computer;
}
Why?
@OneToOne annotation indicates relation between entities.
@SequenceGenerator is redudant since we "copy" id from Computer entity.
@Id annotation is mandatory to indicate that this field is our primary key.
Last but not least, @MapsId annotation do the magic, where it 'borrows' id from relation.
More info in the link I attached earlier.
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.