我是Spring Boot的新手。我有一个具有资源的表(团队),正在存储在一个单独的表(资源)中,并具有team_resource映射表(具有字段teamid,resourceid)。我的问题是我也应该为mapping_table提供一个域类吗?
当我使用资源插入新团队(POST)时,会在所有3个表中创建条目。我正在使用Facade / Dao模式对DB进行写入/读取。当团队被修改/删除时,我必须处理。我应该为mapping_table提供一个域类吗?
答案 0 :(得分:0)
您可以使用多种方法
方法1
在团队和资源实体之间定义@ManyToMany
,如下所示:
在团队实体中
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "resources",
joinColumns = { @JoinColumn(name = "id") },
inverseJoinColumns = { @JoinColumn(name = "id") })
private Set<Resources> resources= new HashSet<>();
在您的资源实体中:
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "resources")
private Set<Team> teams= new HashSet<>();
方法2
@Entity
@Table(name = "team_resources")
public class TeamResources implements Serializable {
@EmbeddedId
private TeamResourcesId id;
@ManyToOne
@JoinColumn(name = "team_id", referencedColumnName = "id", insertable = false, updatable = false)
private Team team;
@ManyToOne
@JoinColumn(name = "resources_id", referencedColumnName = "id", insertable = false, updatable = false)
private Resources resources;
public TeamResources (Team u, Resources r) {
// create primary key
this.id = new TeamResourcesId (u.getUserId(), q.getQuestionId());
// initialize attributes
this.user = u;
this.question = q;
}
@Embeddable
public static class TeamResourcesId implements Serializable {
@Column(name = "team_id")
protected Long teamId;
@Column(name = "resources_id")
protected Long resourcesId;
public TeamResourcesId () {
}
public TeamResourcesId (Long teamId, Long resourcesId) {
this.teamId= teamId;
this.resourcesId= resourcesId;
}
//Getter , setter. equal and hash
}
为回答您的问题,请遵循第二种方法,最好不要定义双向方法,因为如果处理不当,可能会导致运行时问题。