MyBatis-Plus笔记

一.建立库表
库:mp
表:user

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

随便插入一些数据

二.引入依赖


	4.0.0
	com.tiglle
	mybatis-plus
	0.0.1-SNAPSHOT
	war

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.3.RELEASE
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-test
		
		
		
			org.projectlombok
			lombok
			true
		
		
		
            com.baomidou
            mybatis-plus-boot-starter
            3.1.0
        
        
		
			mysql
			mysql-connector-java
		
	


三.mapper文件:

//BaseMapper mybatis-plus的基础mapper
public interface UserMapper extends BaseMapper{

}

四.mybatis plus功能
1.查询所有

List users = userMapper.selectList(null);

2.根据id查询

userMapper.selectById(id);//id可以为Long,String,Integer类型等
userMapper.selectBatchIds(ids);//id可以为Long,String,Integer类型等(集合类型)

3.条件查询

userMapper.selectByMap(Map<表字段, 表字段值>)

4.条件构造器查询

		//两种方法都可以实例化QueryWrapper
		QueryWrapper qw = new QueryWrapper();
//		QueryWrapper qw1 = Wrappers.query();
		qw.like("表字段", "字段值").orderByDesc("表字段");
		
		//in子查询,id in (select id from user where age=20 查询出来的值)
		qw.inSql("id", "select id from user where age=20");

		//apply拼接sql查询
		qw.apply("id={0} and name={1}",20,"小明");
		//有sql注入风险,如
		String name = "前端传入的值"
		qw.apply("id="+name+" and name={1}",20,"小明")
		
		userMapper.selectList(qw);

五.常用注解

@TableName("mp_user")//实体名可以和表名不一致
public class User {}
public class User {
	private long id;
	@TableId//mybatis-plus默认查找id为主键,这里指定user_id为主键
	private long userId;
 @TableField("real_name")//字段名可以和列名不一致
 private String name;

六:排除非表字段的三种方式(实体类拥有的自断并不想与表中的自断关联)

1.加 static关键字
2.加上 transient 关键字
2.加上注解:TableField(exist=false) exist:是否要在表中存在,默认为true

你可能感兴趣的:(MyBatis)