Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaBean转化 #6279

Closed
wants to merge 2 commits into from
Closed

JavaBean转化 #6279

wants to merge 2 commits into from

Conversation

aSingleDragon
Copy link

该Pull Request关联的Issue

修改描述

在使用mapper的selectList方法时,查询一个宽表或者查询的字段占据表总字段数比例较低时,应该用select(Student::getName, Student::getAge)来选择需要的字段。查询出来的实体Bean在分层架构中直接透穿是不安全的,不便理解的,效率较低。此时需要将Bean进行转换成目标Bean。

测试用例

`
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {"classpath:h2/spring-test-h2.xml"})
class H2UserMapperTest extends BaseTest {

@Test
void testSelectAndConvert() {
    List<H2User> h2Users = userMapper.selectList(new LambdaQueryWrapper<H2User>()
        .select(H2User::getTestId, H2User::getAge));
    List<H2Student> h2Students = userMapper.selectAndConvertList(new LambdaQueryWrapper<H2User>()
        .select(H2User::getTestId, H2User::getAge), H2Student.class);
    for (int i = 0; i < h2Students.size(); i++) {
        H2User h2User = h2Users.get(i);
        H2Student h2Student = h2Students.get(i);
        Assertions.assertEquals(h2Student.getName(), h2User.getName());
    }
}

}
class BeanConvertUtilsTest {

@Test
void testConvert() {
    List<Student> studentList = new ArrayList<>();
    Student student = new Student();
    student.setAge(17);
    student.setName("hll");
    student.setGender(true);
    student.setGrade((byte) 99);
    studentList.add(student);
    List<Teacher> teacherList = BeanConvertUtils.convert(studentList, Teacher.class);
    for (int i = 0; i < teacherList.size(); i++) {
        Teacher t = teacherList.get(i);
        Student s = studentList.get(i);
        Assertions.assertEquals(s.getAge(), t.getAge());
        Assertions.assertEquals(s.getName(), t.getName());
        Assertions.assertEquals(s.isGender(), t.isGender());
    }
}

@Data
public static class Man {

    private String home;

}

@Data
public static class Student {

    private static final Integer no = 12;

    private byte grade;

    private int age;

    private String name;

    private boolean gender;

    private Integer salary;
}

@Data
public static class Teacher {

    private Integer age;

    private String name;

    private boolean gender;

    private String clazz;

    private int salary;
}

}`

修复效果的截屏

@miemieYaho
Copy link
Member

这种你留着自己项目里用就行了,mp只需要管大方向

@miemieYaho miemieYaho closed this Jun 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants