Mybatis-plus
Mybatis-plus整合三部曲
1.pom引入mybatis-plus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
2.Spring XML更改配置SqlSessionFactory实现类
在applicationContext.xml中修改SqlSessionFactory实现类
原生Mybatis与Spring整合如下:
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
修改后
<bean id="sessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
3.mybatis-config.xml增加MP分页插件
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/>
</plugins>
举例实现分页:
Mybatis-plus开发三部曲
1.创建实体类,@TableName/@TableId/ @TableField实现映射
@TableName 将实体类与表名映射
@TableId 说明对应的属性是表的主键
@TableField 设置属性与类名映射关系
@TableName("test")//说明实体对应拿一张表
public class Test {
@TableId(type = IdType.AUTO)//主键自增
@TableField("id")//说明属性对应哪个字段
private Integer id;
@TableField("content")//如果字段名与属性名称相同或者符合驼峰命名转换规则,则TableField可省略
private String content;
}
2.创建Mapper接口继承BaseMapper,创建Mapper XML
public interface TestMapper extends BaseMapper<Test> {
}
在resources目录下的mappers文件夹创建对应的Mapper XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace绑定了与之对应的接口,值是该接口的全限定名;这个参数有且只有一个
-->
<mapper namespace="com.imooc.reader.mapper.TestMapper">
</mapper>
3.开发时注入Mapper对象,通过内置API实现CRUD操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MyBatisPlusTest {
@Resource
private TestMapper testMapper;
@org.junit.Test
public void testInsert(){
Test test=new Test();
test.setContent("测试用例");
testMapper.insert(test);
}
@org.junit.Test
public void testUpdate(){
Test test = testMapper.selectById(1);
test.setContent("测试用例1");
testMapper.updateById(test);
}
@org.junit.Test
public void testDel(){
testMapper.deleteById(1);
}
@org.junit.Test
public void testSelect(){
QueryWrapper<Test> queryWrapper=new QueryWrapper<Test>();
//多个queryWrapper查询时使用and连接
queryWrapper.eq("id",3);//查询id=5
queryWrapper.gt("id",5);//查询id>5
List<Test> list = testMapper.selectList(queryWrapper);
System.out.println(list.get(0));
}
}