微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过关系多方面的复合主键持久化数据在关系的多方面

如何解决如何通过关系多方面的复合主键持久化数据在关系的多方面

我遇到了问题,我们将不胜感激。 我有一个可能存在关系的实体,在关系的许多方面大多具有复合主键。 例如,我有两个实体,例如ClientClient_User,并且Client与具有复合主键的Client_User关联,即client_iduser_id ,我想在使用Spring数据Jpa将数据持久存储到Client_User实体时将数据持久存储到Client实体。我的实体如下所示:

@Entity
@Table(name = "client")
public class ClientEntity implements Serializable {
   private int clientId;
   private int userId;
   private Collection<ClientUserEntity> clientUsersByClientId;

   // ...
   
   @OnetoMany(mappedBy = "clientByClientId",fetch = FetchType.LAZY)
   @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
   public Collection<ClientUserEntity> getClientUsersByClientId() {
        return clientUsersByClientId;
   }
   public void setClientUsersByClientId(Collection<ClientUserEntity> clientUsersByClientId) {
        this.clientUsersByClientId = clientUsersByClientId;
   }
}
    
@Entity
@Table(name = "client_user")
@IdClass(ClientUserEntityPK.class)
public class ClientUserEntity implements Serializable {
   private int clientId;
   private int userId;
        
   @Id
   @Column(name = "client_id")
   public int getClientId() {
       return clientId;
   }
   public void setClientId(int clientId) {
       this.clientId = clientId;
   }
        
   @Id
   @Column(name = "user_id")
   public int getUserId() {
      return userId;
   }
   public void setUserId(int userId) {
      this.userId = userId;
   }
  
   @ManyToOne
   @JoinColumn(name = "client_id",referencedColumnName = "client_id",nullable = false,insertable =false,updatable  =false)
   public ClientEntity getClientByClientId() {
      return clientByClientId;
   }
   public void setClientByClientId(ClientEntity clientByClientId) {
      this.clientByClientId = clientByClientId;
   }
}
        
public class ClientUserEntityPK implements Serializable {
   private int clientId;
   private int userId;
    
   @Column(name = "client_id")
   @Id
   public int getClientId() {
      return clientId;
   }
   public void setClientId(int clientId) {
      this.clientId = clientId;
   }
    
   @Column(name = "user_id")
   @Id
   public int getUserId() {
       return userId;
   }
   public void setUserId(int userId) {
       this.userId = userId;
   }
    
   @Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       ClientUserEntityPK that = (ClientUserEntityPK) o;
       return clientId == that.clientId &&
              userId == that.userId;
   }
    
   @Override
   public int hashCode() {
       return Objects.hash(clientId,userId);
   }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。