我试图从一个表中检索一个实体列表,其中包含两个主键,每个主键都是一个外键的ID。
MySQL表:
绘画表:
id - int, PK, Auto increment
name - varchar(45)
图片表:
id - int, PK, Auto increment
name - varchar(45)
location - varchar(45)
painting_to_picture_link table:
painting_id - int, FK to id in painting
picture_id - int, FK to id in painting
I've set primary key (painting_id, picture_id)
and set them to their foreign keys also as written above.
在Java中:
Painting.java
@Entity
@Table(name = "paintings")
public class Painting {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
...
}
Picture.java
@Entity
@Table(name = "pictures")
public class Pictures {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "location")
private String location;
...
}
PaintingPictureLink.class
public class PaintingPictureLink implements Serializable {
@<SOME ANNOTATION HERE>
private Painting painting;
@<SOME ANNOTATION HERE>
private Picture picture;
...
}
我见过很多例子,但对我来说并不适用。 我尝试过@Id注释,@ EmbeddedId等等......没有工作。 我得到的错误是表没有映射,无法确定模型的类型,缺少@Id注释...:|
非常感谢您查询此表并获取PaintingPictureLink列表。
我遵循的一些例子:
Using an Entity (and their Primary Key) as another Entity's Id
谢谢,
盖
答案 0 :(得分:0)
DERP
找到了解决方案。
我创建了一个主键类:
@Embeddable
public class PicturePaintingPK implements Serializable {
@ManyToOne
private Painting painting;
@ManyToOne
private Picture picture;
public PicturePaintingPK() {}
// getters and setters //
}
在PicturePaintingLink类中:
@Entity
@Table(name = "painting_to_picture_link")
public class PaintingPictureLink implements Serializable {
@Id
private PicturePaintingPK primaryKey = new PicturePaintingPK()
...
//constructor//
...
public TTPK getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(TTPK primaryKey) {
this.primaryKey = primaryKey;
}
// ... all the other getters and setters needed .... //
}
此解决方案的来源是:
盖