[英]How can I properly annotate this relationship between two entities using Hibernate & Spring Data JPA?
Goal:目标:
I am building a web app where there is an overview.我正在构建一个有概述的网络应用程序。 In this overview, I load classifieds from a backend.
在本概述中,我从后端加载分类广告。 Each classified has exactly one thumbnail.
每个分类都有一个缩略图。
First, the overview loads the classified, then it attempts to look up the associated thumbnail in the relevant Spring Data JPA Repository using the ID of the Classified.首先,概览加载分类,然后尝试使用分类的 ID 在相关的 Spring Data JPA 存储库中查找关联的缩略图。
Current state: The Classified table looks OK.当前状态:分类表看起来不错。 The Thumbnail table is missing a reference to the Classified.
缩略图表缺少对分类的引用。
Desired state: I want the Thumbnail table to contain a reference to the ID of the classified, so that I can query the Thumbnail of a Classified.期望状态:我希望 Thumbnail 表包含对分类 ID 的引用,以便我可以查询分类的 Thumbnail。
ERD(~ish): ERD(~ish):
Entity classes:实体类:
Classified:分类:
import javax.persistence.*;
@Entity
public class Classified {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String summary;
private String description;
public Classified() { }
public Classified(String summary, String description) {
this.summary = summary;
this.description = description;
}
public long getId() {
return id;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Thumbnail:缩略图:
import javax.persistence.*;
@Entity
public class Thumbnail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToOne
@JoinColumn(name = "id")
private Classified classified;
@Column(name="bytes", columnDefinition="VARBINARY(10000)")
private byte[] bytes;
public Thumbnail() {
}
public Thumbnail(Classified classified, byte[] bytes) {
this.classified = classified;
this.bytes = bytes;
}
}
Tables (initiated with some sample data):表格(以一些样本数据开始):
You should change only the name of JoinColumn in the thumbnail class, for example:您应该只更改缩略图类中 JoinColumn 的名称,例如:
@JoinColumn(name = "classifiedId",referencedColumnName = "id")
private Classified classified;
to give a name for the column为列命名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.