首页 > 解决方案 > 映射表所需的Spring Boot域类

问题描述

我是 Spring Boot 的新手。我有一个包含资源的表(团队),存储在一个单独的表(资源)中,并且有 team_resource 映射表(带有字段 teamid、resourceid)。我的问题是我是否也应该为 mapping_table 提供一个域类?

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

标签: spring-bootgrails-domain-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
}

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


推荐阅读