【问题标题】:Spring boot domain class required for mapping table映射表所需的Spring Boot域类
【发布时间】:2023-03-06 02:59:02
【问题描述】:

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

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

【问题讨论】:

    标签: spring-boot grails-domain-class


    【解决方案1】:

    有多种方法可以处理它

    方法 1

    在您的团队和资源实体之间定义@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<>();
      

    方法 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
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2019-11-25
      • 2017-12-24
      • 2018-03-18
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多