官网: https://baomidou.com/pages/24112f/
MyBatis-Plus简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
愿景
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `tb_user`(`id`, `username`, `password`, `name`, `age`, `email`) VALUES (1, 'zhangsan', '123', '张三', 12, 'zhangsan@126.com');
INSERT INTO `tb_user`(`id`, `username`, `password`, `name`, `age`, `email`) VALUES (2, 'xiaogeng', '234', '小耿', 15, 'xiaogen@126.com');
INSERT INTO `tb_user`(`id`, `username`, `password`, `name`, `age`, `email`) VALUES (3, 'laofeng', '456', '老冯', 21, 'laofeng@126.com');
INSERT INTO `tb_user`(`id`, `username`, `password`, `name`, `age`, `email`) VALUES (5, 'laohan', '888', '老韩', 30, NULL);
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.10version>
<scope>testscope>
dependency>
public interface UserMapper extends BaseMapper<User> {
}
package com.linjiu.model;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName()
public class User {
private int id;
private String username;
private String password;
private String name;
private int age;
private String email;
}
package com.linjiu;
import com.linjiu.dao.UserMapper;
import com.linjiu.model.User;
import com.linjiu.service.IAccountService;
import com.linjiu.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application.xml"})
public class SmTest {
@Autowired
private IUserService userService;
@Test
public void testQueryAll(){
List<User> users = userService.queryAll();
System.out.println(users);
}
}
我们没有写过sql语句,但是我们可以直接使用BaseMapper中的方法,可以省去我们写sql的麻烦。
加在实体类上的,@TableName(表名)
在给数据库插入数据的时候,可以通过给实体类id字段添加注解实现id的自动插入。@TableId(type = IdType.AUTO),一般使用自增。type = IdType.AUTO
1、对象中的属性名和字段名不一致的问题(非驼峰)
2、对象中的属性字段在表中不存在的问题
3、对象中的属性字段在表中不查询。
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("tb_user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField("username")
private String username;
@TableField(select = false)
private String password;
@TableField("name")
private String name;
@TableField("age")
private Integer age;
@TableField("email")
private String email;
@TableField(exist = false)
private String address;
}
如果我们使用mybatis-plus, 那么我们实体类的属性不能使用基本数据类型。
根据给定的属性插入数据,没有指定的属性为null, id不给定会自增
@Test
public void add() {
User user = User.builder().username("laohan").name("林玖").password("888").age(30).build();
int insert = userMapper.insert(user);
System.out.println(insert>0?"成功":"失败");
}
根据id修改,所以必须指定id的值,对象中没有指定的属性不修改。
@Test
public void testUpdateById(){
User user = User.builder().id(2).age(22).build();
if(userMapper.updateById(user)>0){
System.out.println("OK");
}else {
System.out.println("error");
}
}
根据条件修改,QueryWrapper方法比较多,一会专门讲一下QueryWrapper。
@Test
public void testUpdate(){
User user = User.builder().username("laohan").age(22).build();
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.ge("username", "林玖");
if(userMapper.update(user,wrapper)>0){
System.out.println("OK");
}else {
System.out.println("error");
}
}
根据id删除数据
@Test
public void deleteById() {
int i = userMapper.deleteById(4);
System.out.println(i>0?"成功":"失败");
}
将columnMap中的元素设置为删除的条件,多个之间为and关系
@Test
public void deleteByMap() {
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age", 30);
columnMap.put("name", "林玖"); //将columnMap中的元素设置为删除的条件,多个之间为and关系
int i = this.userMapper.deleteByMap(columnMap);
System.out.println(i > 0 ? "成功" : "失败");
}
根据id批量删除, 不存在的id不删除
@Test
public void deleteByIds() {
List<Long> ids = Stream.of(1L, 2L, 3L,8L).collect(Collectors.toList());
int i = userMapper.deleteBatchIds(ids);
System.out.println(i);
}
根据id查询
根据id列表查询
wrapper 条件 相当于我们sql语句中where后面的部分
如果wrapper有多个条件,默认使用and拼接
一般我们用QueryWrapper就可以了
int delete(@Param("ew") Wrapper wrapper);
@Test
public void deleteByCondition() {
// 构建条件
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 构建map
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("age", 23);
columnMap.put("name", "林玖");
// 所有的条件都要满足才能删除
wrapper.allEq(columnMap);
int delete = userMapper.delete(wrapper);
System.out.println(delete);
}
eq 等于 =
@Test
public void selectOne() {
// 构建条件
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "林玖");
User user = userMapper.selectOne(wrapper);
System.out.println(user);
}
ne 不等于 <>
gt 大于 >
ge 大于等于 >=
lt 小于 <
le 小于等于 <=
between BETWEEN 值1 AND 值2
notBetween NOT BETWEEN 值1 AND 值2
in 字段 IN (value.get(0), value.get(1), …)
notIn 字段 NOT IN (v0, v1, …)
like LIKE ‘%值%’ 例: like(“name”, “王”) —> name like ‘%王%’
notLike NOT LIKE '%值%
likeLeft LIKE ‘%值’ 例: likeLeft(“name”, “王”) —> name like ‘%王’
likeRight LIKE ‘值%’ 例: likeRight(“name”, “王”) —> name like ‘王%’
orderBy 排序:ORDER BY 字段, …
orderByAsc 排序:ORDER BY 字段, … ASC 例: orderByAsc(“id”, “name”) —> order by id ASC,name ASC
orderByDesc 排序:ORDER BY 字段, … DESC 例: orderByDesc(“id”, “name”) —> order by id DESC,name DESC
or 拼接 OR 主动调用 or 表示紧接着下一个方法不是用 and 连接!(不调用 or 则默认为使用 and 连接)
and AND 嵌套
例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”)) —> and (name = ‘李白’ and status
<> ‘活着’)