hibernate 多对多关系休眠中的子实体数据丢失

7fhtutme  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(140)

下面是许多关系,其中用户保存到用户表中,并且在user_role表中也有条目,但在角色表中添加的条目缺少名称字段值?

@Table(name = "users")
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class Users implements Serializable {
    @Id
    String id;

    String username;
    String password;

    @ManyToMany(cascade = {CascadeType.PERSIST}, fetch = FetchType.EAGER)
    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles = new ArrayList<>();
}

@Table(name = "role")
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@ToString
@EqualsAndHashCode
public class Role implements Serializable {

    @Id
    @GeneratedValue
    @Type(type = "uuid-char")
    UUID id;

    @Column(name = "name")
    String name;
}

@Repository
public interface UsersRepository extends JpaDynamicQueryRepository<Users, String> {
}

public void save(){
Users users = new Users();
        users.setUsername("ui-user");
        users.setPassword("ui1234");
        users.setId(UUID.randomUUID().toString());
        Role adminRole = Role.builder()
                .name("ui-role")
                .build();

        Role testRole = Role.builder()
                .name("ui-test-role")
                .build();

        List<Role> roles = new ArrayList<>();
        roles.add(adminRole);
        roles.add(testRole);
        users.setRoles(roles);
        usersRepository.saveAndFlush(users);
}

记录插入下面的一个

已添加带有uuid的条目,但未保存名称。

vltsax25

vltsax251#

尝试找出注解'@ ManyToMany'的含义,使用'@ManyToMany(cascade = {CascadeType.ALL}'而不是您的注解。

相关问题