JPA操作多对多中间表CRUD

阅读更多

authority 角色

permission 权限

authority_permission 中间表

现在要对中间表进行操作,但是中间表的两个字段分别是两个主表的外键,而不是主键,所以要给这张中间表创建一个联合主键,然后就可以对中间表进行操作了,

详见

AuthorityPermission.java

AuthorityPermissionId.java 

 

@Entity
@Table(name = "authority", schema = "msa")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Data
public class Authority {

    @Size(min = 1, max = 20)
    @Id
    @Column(length = 20)
    private String name;

@JsonIgnore
    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(schema = "msa", name = "authority_permission",
joinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")},
inverseJoinColumns = {@JoinColumn(name = "permission_id", referencedColumnName = "id")})
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @BatchSize(size = 50)
    private Set permissions = new HashSet<>();

@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(schema = "msa", name = "user_authority",
joinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")},
inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")})
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @BatchSize(size = 20)
    private Set users = new HashSet<>();
}

 

 

@Entity
@Table(name = "permission", schema = "fund")
@Data
@EntityListeners(AuditingEntityListener.class)
public class Permission {
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    private Long id;

@Size(min = 3, max = 20)
    private String name;

@Size(max = 50)
    private String description;

    private Long parentId;

@Size(max = 50)
    private String page;

@CreatedBy
private String createdBy;

@CreatedDate
private Date createdTime;
}

 

@Entity
@Data
@Table(name = "authority_permission", schema = "msa")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuthorityPermission {

    @EmbeddedId
private AuthorityPermissionId id;


}

 

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AuthorityPermissionId implements Serializable {

    @Column(name = "authority_name")
    private String AuthorityName;

@Column(name = "permission_id")
    private Long PermissionId;

}

 

你可能感兴趣的:(多对多中间表CRUD,多对多中间表增删改)