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

问题描述

我遇到了问题,我们将不胜感激。 我有一个可能存在关系的实体,在关系的许多方面大多具有复合主键。 例如,我有两个实体,例如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 (将#修改为@)