spring数据jpa集合不更新

ukdjmx9f  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(339)

嗨,我有两个实体:部门和用户。
我找到这两个实体,并希望将其中一个添加到另一个实体,但如果我将用户添加到部门,则该用户的department=null。如果相反的是真的,那么list=null。如何正确操作?

@Entity
@Table(name = "department")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {

    @Id
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "uuid2")
    @Column(length = 36, nullable = false, updatable = false)
    private UUID id;

    @Column(name = "name", nullable = false)
    private String name;
    @Column(name = "description", nullable = false)
    private String description;
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
    private List<User> users = new ArrayList<>();

}

@Entity
@Table(name = "user")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {

    @Id
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "uuid2")
    @Column(length = 36, nullable = false, updatable = false)
    private UUID id;

    private String firstName;
    private String lastName;
    private Integer age;

    @ManyToOne
    private Department department;

    @ManyToMany
    @JoinTable(
            name = "device_devices",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "device_id"))
    Set<Device> devices = new HashSet<>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equal(id, user.id);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }
}

和服务

@Override
@Transactional
public void addUserToDepartment(UUID departmentId,UUID userId){
    Department department = departmentRepository.findById(departmentId).orElseThrow(DepartmentNotFoundException::new);
    User user = userRepository.findById(userId).orElseThrow(UserNotFoundException::new);
    department.getUsers().add(user);
    //user.setDepartment(department);
}

在我看来,将用户添加到部门并同时将部门添加到用户是不正确的。他们必须振作起来。帮助我

moiiocjp

moiiocjp1#

这就是为什么你 mappedBy 属性。当您有一个双向Map时,它提示休眠哪一方将负责这些Map。
所以考虑到你的配置

public class Department {
 @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
    private List<User> users = new ArrayList<>();

    ...
    }

那么只在FieldDepartment的用户上设置Map就足够了

@Override
@Transactional
public void addUserToDepartment(UUID departmentId,UUID userId){
    Department department = departmentRepository.findById(departmentId).orElseThrow(DepartmentNotFoundException::new);
    User user = userRepository.findById(userId).orElseThrow(UserNotFoundException::new);
    //department.getUsers().add(user); You don't need this.
    user.setDepartment(department); This here is enough for hibernate!
}

但是

正如hibernate文档所指出的,为了在一个方法中有正常的java用法,您需要手动更新两边。这意味着,如果只更新一个端,那么更改将在db级别上持久化,但在java级别上,您的另一个示例将不会与这些更改同步。
检查hibernate文档中的以下示例(示例297、示例298)hibernate双向Map正常java用法

lhcgjxsq

lhcgjxsq2#

双向关系必须由你手动维护,没有魔术发生在幕后为你处理。
处理服务内代码的另一种方法是增强连接属性的设置程序来处理该代码,例如在用户端:

public void setDepartment(Department department) {
    this.department = department;
    department.getUsers().add(this);
}

有关文档,请参阅此处。

相关问题