在JPA中保持一对多关系

时间:2019-03-30 11:49:51

标签: java hibernate jpa

我有这两个实体,其中作为权限列表的组和一个权限属于一个组:

GroupClass:

@Entity
@Table(name = "group")
public class GroupEntity {

@Id
private String name;

@OneToMany(mappedBy = "group",cascade = {CascadeType.ALL})
private Set<Permission> permissions;

public GroupEntity() {

}

public GroupEntity(String name,Permission ...permissions) {
    this.name = name;
    this.permissions = Stream.of(permissions).collect(Collectors.toSet());
    this.permissions.forEach(x -> x.setGroup(this));
}

权限等级:

@Entity

公共类权限{

@Id
@GeneratedValue
private Long id;

private String permissionName;

@ManyToOne
private GroupEntity group;

public Permission() {

}

public Permission(String permissionName) {
    this.permissionName = permissionName;
}

要保留许可,我这样做:

    Permission p2=new Permission("permission2");
    permissionRepository.save(p2);

    GroupEntity r1 = new GroupEntity("group",p2);   
    groupRepository.save(r1);

我认为,如果我这样做的话,它可以代替它,但事实并非如此:

    Permission p2=new Permission("permission2");
    permissionRepository.save(p2);

    GroupEntity r1 = new GroupEntity("group");  
    p2.setGroup(r1);
    permissionRepository.save(p2);
    groupRepository.save(r1);

谢谢!

0 个答案:

没有答案