/** * 名字里包含"A",且年龄小于20的 * 问题描述:执行,报错 Cause: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 * 去掉select("id", "name"),执行正常,返回两条记录. */ @Test public void selectByWrapperSuper1(){ QueryWrapper<User> query = Wrappers.query(); QueryWrapper<User> queryWrapper = query.select("id", "name").like("name", "A") .lt("age", 20); List<User> userList = userMapper.selectList(queryWrapper); userList.forEach(System.out::println); }
同学找到原因了,是你在实体中加了@Builder注解的问题,把这个注解去掉就好使了,这个注解加上之后,应该就不生成作用域为public的构造方法了,而是通过建造者模式创建实体类。
还有,你使用的是MP的什么版本?
正常情况下不应该报错啊,数据库中有id字段吗?还有你没必要使用两个QueryWrapper变量,用一个设置查询条件即可。
@Builder注解不用去掉,User实体类增加两个注解即可
@AllArgsConstructor
@NoArgsConstructor
https://github.com/AllenHv/test
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.thdbd</groupId> <artifactId>first</artifactId> <version>1.0-SNAPSHOT</version> <!--Spring Boot Starter父工程--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> </parent> <dependencies> <!--SpringBoot启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--SpringBoot test启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> <scope>test</scope> </dependency> <!-- Lombok简化JAVA代码 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- Mybatis-Plus启动器 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.2</version> </dependency> <!-- Mysql JDBC 不用指定version,依赖的spring jdbc已指定 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.9.RELEASE</version> <scope>test</scope> </dependency> </dependencies> </project>
以上是我的pom
/** * 名字里包含"A",且年龄小于20的 */ @Test public void selectByWrapperSuper1(){ QueryWrapper<User> query = Wrappers.query(); query.like("name", "A") .lt("age", 40); List<User> userList = userMapper.selectList(query); userList.forEach(System.out::println); }
有Id字段的,上面这串代码可以查询到结果.