sharp-database中的BaseDAOImpl实现多表级联@ManyToMany(三)

级联查询,在中间表中建立关系。不会级联更新!!!

创建实体对象

Usre.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table("t_user")
public class User extends BasePureEntity {

    private String name;

    @ManyToMany(thirdPartyTable = "t_user_role", referenceColumnName = "role_id", columnDefinition = "user_id", referenceTable = "t_role")
    private List<Role> roleList;

}

Role.java

/**
 * @author Rick
 * @createdAt 2022-03-03 19:26:00
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table("t_role")
public class Role extends BasePureEntity {

    private String name;

}

生成3张表 t_user t_role t_user_role。中间表t_user_role 只有三个字段 user_id role_id is_deleted 级联删除的时候需要该字段。

添加测试

    @Test
    public void testInsert() {
        User user = User.builder()
                .name("Rick")
                .roleList(Arrays.asList(Role.builder().id(530861443353075712L).build()))
                .build();

        int count = personDAO.insert(user);
        assertThat(count).isEqualTo(1);

        Optional<User> personOptional = personDAO.selectById(user.getId());
        User person2 = personOptional.get();
        assertThat(person2.getRoleList().get(0).getName()).isEqualTo("admin");
    }

    @Test
    public void testUpdate() {
        User user = User.builder()
                .id(530865367078330368L)
                .name("Tom")
                .roleList(Arrays.asList(Role.builder().id(530861443353075712L).build()
//                        , Role.builder().id(530861443353075713L).build()
                        , Role.builder().id(530861443353075714L).build())
                )
                .build();

        personDAO.update(user);
    }

    @Test
    public void testSelect() {
        Optional<User> personOptional = personDAO.selectById(530864959987572736L);
        User user = personOptional.get();
        assertThat(user.getRoleList().get(0).getName()).isEqualTo("admin");
    }

    @Test
    public void testDelete() {
        personDAO.deleteById(530865367078330368L);
    }