MyBatis-Plus学习LambdaQueryWrapper
一、代码以及配置
1、数据库
CREATE TABLE `med_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`pass_word` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `my_test`.`med_user`(`id`, `user_name`, `pass_word`) VALUES (1, 'root', '123456');
INSERT INTO `my_test`.`med_user`(`id`, `user_name`, `pass_word`) VALUES (2, 'admin', '654321');
2、依赖
<!--lombok工具免生成get,set-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.14</version>
</dependency>
<!-- mybatis plus 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 阿里巴巴druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
3、配置文件
#端口
server:
port: 8088
#数据库
spring:
datasource:
druid:
url: jdbc:mysql://123.123.123.123/my_test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123123
driver-class-name: com.mysql.cj.jdbc.Driver
# 连接池的配置信息
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#mybatis-plus
mybatis-plus:
#映射mapper.xml文件存放路径
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
type-aliases-package: com.example.myjavatest.entity
configuration:
#下划线转驼峰配置
map-underscore-to-camel-cas: true
#使用二级缓存容易出现脏读,建议避免使用二级缓存
cache-enabled: false
4、配置类
@Configuration
@MapperScan("com.example.myjavatest.mapper")
public class MybatisPlusConfigurer {
}
5、实体类
@Getter
@Setter
@TableName("med_user")
public class User implements Serializable {
private Integer id;
private String userName;
private String passWord;
@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.equals(id, user.id) && Objects.equals(userName, user.userName) && Objects.equals(passWord, user.passWord);
}
@Override
public int hashCode() {
return Objects.hash(id, userName, passWord);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
'}';
}
}
6、持久层
public interface UserMapper extends BaseMapper<User> {
}
7、测试方法
@Autowired
UserMapper userMapper;
@Test
void contextLoad13() {
//条件
LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
userLambdaQueryWrapper.eq(User::getId,1);
//查询
List<User> userList = userMapper.selectList(userLambdaQueryWrapper);
userList.forEach(s ->{
System.out.println(s.toString());
});
}
8、结果
二、其他
1、::作用
然后从图片中可以得出::在java8中的作用就是获得方法
2、LambdaQueryWrapper对象使用
LambdaQueryWrapper是mybatis plus中的一个条件构造器对象,只是是需要使用Lambda 语法使用 Wrapper