依赖
1、mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、mybatis-plus
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
</dependency>
3、配置文件连接数据库
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis-plus?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&verifyServerCertificate=false&serverTimezone=Asia/Shanghai
username: root
password: "12345"
driver-class-name: com.mysql.cj.jdbc.Driver
4、创建Mapper接口继承BaseMapper,注意泛型一定要写目标实体类!!!并且添加注解@Repository,把该接口实现对象注册在容器中。
@Repository
public interface UserMapper extends BaseMapper<User> {
}
5、细心的人会发现,我们没有指定表给mybatis-puls框架,他是如何识别哪个表呢,其实他是将我们实体类的驼峰命名全部转化为小写且下划线隔开对应找数据库中表。
例如:实体类User,自动找数据库中的user表
实体类SchoolUser,自动找数据库school_user表
6、在启动类上添加注解@MapperScan扫描Mapper接口的位置
@SpringBootApplication
@MapperScan("com.john.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
7、使用
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
System.out.println("------------");
List list = userMapper.selectList(null);
list.forEach(System.out::println);
}
}
8、可以配置sql日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
9、id的几种生成方式
在实体类的id属性上添加注解@Tableid
@TableId(type = IdType.AUTO)
private Long id;
AUTO(0),//自动配置id,如果表ID设置了自增,则可以使用,如果没有则会报错
NONE(1),//未设置主键,如果修饰的属性是主键,则自动生成全局id
INPUT(2),//手动设置id
ID_WORKER(3),//生成默认全局id
UUID(4),//生成全局id
ID_WORKER_STR(5);//生成全局id的字符串
配置xml文件目录
MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置
注意
Maven 多模块项目的扫描路径需以 classpath*:
开头 (即加载多个 jar 包下的 XML 文件)
增删改查
select
1、selectList()传入null可以查询所有数据库数据
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
sql日志 :
==> Preparing: SELECT id,name,age,email FROM user
==> Parameters:
<== Columns: id, name, age, email
<== Row: 1, john, 99, test1@baomidou.com
<== Row: 2, Jack, 20, test2@baomidou.com
<== Row: 3, Tom, 28, test3@baomidou.com
<== Row: 4, Sandy, 21, test4@baomidou.com
<== Row: 5, Billie, 24, test5@baomidou.com
<== Row: 111, heheh, 17, 12123@qq.com
<== Row: 1432229913269583874, asd, 17, 12123@qq.com
<== Row: 1432233717083901954, heheh, 17, 12123@qq.com
<== Total: 8
2、 selectById(id)传入表中的字段id,查询目标数据
T selectById(Serializable id);
sql日志 :
==> Preparing: SELECT id,name,age,email FROM user WHERE id=?
==> Parameters: 111(Integer)
<== Columns: id, name, age, email
<== Row: 111, heheh, 17, 12123@qq.com
<== Total: 1
3、selectBatchIds()传入一个List集合,查询id集合中所有数据
void selectBatchIdsTest(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
}
sql日志:
==> Preparing: SELECT id,name,age,email,create_time,update_time FROM user WHERE id IN ( ? , ? , ? )
==> Parameters: 1(Integer), 2(Integer), 3(Integer)
<== Columns: id, name, age, email, create_time, update_time
<== Row: 1, john, 99, test1@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Row: 2, Jack, 20, test2@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Row: 3, Tom, 28, test3@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Total: 3
4、 selectByMap(map)通过列名作为key,值作为value进行条件查询。
void selectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","mima");
List<User> users = userMapper.selectByMap(map);
}
sql日志:
==> Preparing: SELECT id,name,age,email,create_time,update_time FROM user WHERE name = ?
==> Parameters: mima(String)
<== Columns: id, name, age, email, create_time, update_time
<== Row: 1432258043602432002, mima, 28, 12123@qq.com, 2021-08-30 16:25:02, null
<== Total: 1
5、selectpage()通过配置分页拦截器进行分页查询,先查询表的个数再进行分页,效率不高。
底层还是使用limit。
@MapperScan("com.john.demo.mapper")
@Configuration
public class mybatisconfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
void selectPage(){
Page<User> page = new Page<>(1,3);//前者是页数,后者是每页个数
userMapper.selectPage(page,null);
}
==> Preparing: SELECT COUNT(1) FROM user
==> Parameters:
<== Columns: COUNT(1)
<== Row: 6
==> Preparing: SELECT id,name,age,email,create_time,update_time FROM user LIMIT ?,?
==> Parameters: 0(Long), 3(Long)
<== Columns: id, name, age, email, create_time, update_time
<== Row: 1, john, 99, test1@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Row: 2, Jack, 20, test2@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Row: 3, Tom, 28, test3@baomidou.com, 2021-08-30 15:48:05, 2021-08-30 15:48:05
<== Total: 3
insert
insert()传入一个实体类,添加数据
int insert(T entity);
sql日志:
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1432241829446582274(Long), heheh(String), 17(Integer), 12123@qq.com(String)
<== Updates: 1
返回值为更新数据的条数。
updata
updata() 传入一个实体类,通过实体类的id属性修改数据
int updateById(@Param("et") T entity);
sql日志:
==> Preparing: UPDATE user SET name=?, age=? WHERE id=?
==> Parameters: john(String), 99(Integer), 1(Long)
<== Updates: 1
delete
deleteById(id)传入字段id的值,进行删除数据
int deleteById(Serializable id);
sql日志:
==> Preparing: DELETE FROM user WHERE id=?
==> Parameters: 1432229913269583874(Long)
<== Updates: 1
自动填充
应用:自动填充时间
在时间属性上添加注解@TableField(fill = FieldFill.INSERT)代表插入时自动填充数据
public enum FieldFill {
DEFAULT,//默认不填充
INSERT,//插入时填充
UPDATE,//更新时填充
INSERT_UPDATE;//插入和填充时填充
private FieldFill() {
}
}
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
然后编写一个类,实现MetaObjectHandler接口,重写insertFill()和updateFill()方法,前者方法插入时运行,后者方法更新时运行。注意:一定要把该类注册在spring的ioc容器中,否则不生效
@Component
public class datehandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
setFieldValByName(String fieldName, //需要自动填充的属性名
Object fieldVal, //需要自动填充的值
MetaObject metaObject)//把上面的metaObject传入