我在DB中有一个表“seance”('id'是PK):
CREATE TABLE seance(
id int NOT NULL AUTO_INCREMENT,
seance_id int,
number int,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
降神
id, seance_id, number
1, 111222, 1951
2, 111222, 1951
3, 111222, 1951
4, 333222, 1415
5, 333222, 1415
6, 333222, 1415
实体类:
@Entity
@Table(name = "seance")
public class Seance {
public Seance() {}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "seance_id")
private Integer seanceId;
@Column(name = "number")
@ElementCollection// it is wrong cause require TWO tables
//what I should write here or modify?
private Set<Integer> number = new HashSet<Integer>();
public Seance(Integer seanceId, Set<Integer> number) {
this.seanceId = seanceId;
this.number = number;
}
// getters and setters
}
因此我希望有一个Seance类的实例:
Integer seanceId:111222;
编号:1951,1951,1951;
答案 0 :(得分:1)
是的,它用于处理多个非标准关系映射,ElementCollection
可用于定义一对多关系,ElementCollection
值始终存储在单独的表中。
答案 1 :(得分:1)
你需要拥有这样的实体:
@Entity
@Table(name = "seance")
public class Seance {
public Seance() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "seance_id")
private Integer seanceId;
@ElementCollection
@CollectionTable(
name="NUMBER",
joinColumns=@JoinColumn(name="OWNER_ID")
)
private Set<Integer> number = new HashSet<Integer>();
public Sessions(Integer seanceId, Set<Integer> number) {
this.seanceId = seanceId;
this.number = number;
}
public Integer getSeanceId() {
return seanceId;
}
public void setSeanceId(Integer seanceId) {
this.seanceId = seanceId;
}
public Set<Integer> getNumber() {
return number;`enter code here`
}
public void setNumber(Set<Integer> number) {
this.number = number;
}
}
这样做,你将有两个表,数字将有一个表,没有和实体。此外,您的概念是事件不好,因为您在使用DataBases进行处理时需要避免冗余。 你也可以点这个链接 https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection