spring-boot - 映射表所需的Spring Boot域类
问题描述
我是 Spring Boot 的新手。我有一个包含资源的表(团队),存储在一个单独的表(资源)中,并且有 team_resource 映射表(带有字段 teamid、resourceid)。我的问题是我是否也应该为 mapping_table 提供一个域类?
当我使用资源插入一个新团队 (POST) 时,我在所有 3 个表中创建条目。我正在使用外观/dao 模式来写入/读取数据库。当团队被修改/删除时,我必须处理。我应该有一个映射表的域类吗?
解决方案
有多种方法可以处理它
方法一
在您的团队和资源实体之间定义@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<>();
方法二
@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
}
因此,要回答您的问题,请遵循第二种方法,最好不要定义双向方法,因为如果处理不当,可能会导致一些运行时问题。
推荐阅读
- python - 在python中验证http响应
- elasticsearch - 使用 CloudID、用户名和密码连接到 Elasticsearch
- sql-server - 将多个具有关系的 EXCEL 文件(Vlookup)导入 MS SQL Server
- android - 如何阻止相同的广播(来自 PendingIntent)排队?
- amazon-web-services - amazon s3 预签名的 url 应该使用新的访问密钥辞职
- javascript - 将数组传递给 JavaScript 显示为 Object
- java - jhipster为什么不更新
- html - 使用 css 反映 svg
- android - Firebase 验证 Id 令牌,但客户端尚未准备好,所以我不知道来自客户端的数据包含
- css-selectors - DomCrawler 第二个等孩子