Spring 映射需要引导域 class table

Spring boot domain class required for mapping table

我是 Spring Boot 的新手。我有一个 table(团队),它有资源,我存储在一个单独的 table(资源)中,并且有 team_resource 映射 table(带有字段 teamid、resourceid)。我的问题是我也应该为 mapping_table 设置一个域 class 吗?

当我插入具有资源的新团队 (POST) 时,我在所有 3 个 table 中创建条目。我正在使用 facade/dao 模式写入/读取数据库。当团队被修改/删除时,我必须处理。 mapping_table 我应该有一个域 class 吗?

有多种方法可以处理它

方法一

像这样在您的团队和资源实体之间定义@ManyToMany

  1. 在团队实体中

    @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<>();
    
  2. 在您的资源实体中:

     @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
}

所以要回答你的问题,请遵循第二种方法,最好不要定义双向方法,因为如果处理不当,它可能会导致一些 运行 时间问题。