-
- <groupId>com.github.pagehelpergroupId>
- <artifactId>pagehelperartifactId>
- <version>5.3.0version>
-
- <plugins>
- <plugin interceptor="com.github.pagehelper.PageInterceptor">
- <property name="offsetAsPageNum" value="true"/>
-
-
-
- <property name="rowBoundsWithCount" value="true"/>
-
- <property name="reasonable" value="true"/>
- plugin>
- plugins>

三步走:
//配置要访问的页码和每页的记录数
PageHelper.startPage(1,3)
//执行自己的查询方法
.........
//用分页插件中的工具类来封装查询结果,这个对象就是封装好的分页结果对象
new PageInfo<>(mapper.goodsList())
MyBatis拦截器为了供用户在某些时候可以实现自己的逻辑而不必去动MyBatis固有的逻辑;通过MyBatis拦截器我们可以拦截某些方法的调用,我们可以选择在这些被拦截的方法执行前后加上某些逻辑,也可以在执行这些被拦截的方法时执行自己的逻辑而不再执行被拦截的方法。
MyBatis拦截器并不是每个对象里面的方法都可以被拦截的,拦截器只能拦截Executor、ParameterHandler、StatementHandler、ResultSetHandler四个对象里面的方法,MyBatis允许在映射语句执行过程中的某一点进行拦截调用,默认情况下,MyBatis允许使用插件来拦截的方法调用包括:
| 对象名称 | 对象作用 |
| ParameterHandler | 处理用户提交参数对象 |
| StatementHandler | 预编译SQL语句对象 |
| Executor | 执行SQL语句对象 |
| ResultSetHandler | 处理返回结果集对象 |
Executor 是 Mybatis 的内部执行器,负责调用StatementHandler操作数据库,并把结果集通过 ResultSetHandler 进行自动映射,同时还处理了二级缓存的操作(故我们可以通过插件来实现自定义的二级缓存);
StatemenHandler 是 Mybatis 直接和数据库执行 sql 脚本的对象,也实现了Mybatis的一级缓存(可以使用插件来实现对一级缓存的操作(禁用等));
ParameterHandler 是 Mybatis 实现 Sql 入参设置的对象(插件可以该改变sql的参数默认设置);
ResuSetHandler 是 Mybatis 把 ResultSet 集合映射成 POJO 的接口对象(可以定义插件对Mybatis 的结果集自动映射进行修改)。
只需要实现 interceptor 接口,并指定想要拦截的方法签名即可。
- @Intercepts(
- @Signature(
- type = StatementHandler.class,
- method = "prepare",
- args = {Connection.class,Integer.class}
- )
- )
- public class MyPageInterceptor implements Interceptor {
-
- }
| 属性名称 | 属性作用 |
| @Intercepts | 标记这是一个interceptor |
| @Signature | 定义拦截点 |
| @type | 拦截对象 |
| @method | 拦截对象中的某一个方法 |
| @args | 拦截方法上对应的参数 |
- public interface Interceptor {
- Object intercept(Invocation invocation) throws Throwable;
-
- Object plugin(Object target);
-
- void setProperties(Properties properties);
- }
intercept :直接覆盖所拦截的对象,有个参数 invocation 对象,通过改对象可以反射调度原来对象的方法;
plugin:target 是被拦截的对象,用于给被拦截对象生成一个代理对象;
setProperties:允许在plugin元素中配置所需参数,该方法在插件初始化的时候会被调用一次。
Mybatis 在执行 sql 语句前会产生一个包含 Sql 语句的 Statement 对象,在 生成 statement 之前修改 sql 语句,把 原来的sql 语句改成对应分页查询 sql 语句。
- <plugins>
- <plugin interceptor="com.interceptor.MyPageInterceptor">
- <property name="start" value="0"/>
- <property name="end" value="3"/>
- plugin>
- plugins>
- public class MyPageInterceptor implements Interceptor {
- private String start;
- private String end;
- @Override
- public Object intercept(Invocation invocation) throws Throwable {
- Object target = invocation.getTarget();
- MetaObject metaObject = SystemMetaObject.forObject(target);
- String oldSql = metaObject.getValue("delegate.boundSql.sql").toString();
-
- System.out.println("oldSql:"+oldSql);
-
- String newSql = oldSql+" limit "+start+","+end;
- System.out.println("newSql"+newSql);
-
- metaObject.setValue("delegate.boundSql.sql",newSql);
-
- return invocation.proceed();
- }
-
- @Override
- public Object plugin(Object target) {
- if(target instanceof StatementHandler){
- return Plugin.wrap(target, this);
- }
- return target;
- }
-
- @Override
- public void setProperties(Properties properties) {
- start = properties.getProperty("start");
- end = properties.getProperty("end");
- }
- }
通用mapper的作用,在mybatis框架基础上,封装了单表增删改查的操作(不需要定义mapper文件,就可以实现相应功能)
- <dependency>
- <groupId>com.github.abel533groupId>
- <artifactId>mapperartifactId>
- <version>3.0.1version>
- dependency>
- <plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
-
-
-
- <property name="mappers" value="com.github.abel533.mapper.Mapper" />
- plugin>
- public interface IGoodsDaoCo extends Mapper
{ - }
- @Data
- @Table(name = "tb_goods")
- public class Goods implements Serializable {
- @Id
- private Integer goodsId;
- @Column(name = "goods_name")
- private String goodsName;
- private Double price;
- private Date produceDate;
- private String address;
- private Integer categoryId;
- }
- @Test
- public void IGoodsDaoCo(){
- IGoodsDaoCo mapper = session.getMapper(IGoodsDaoCo.class);
- List
select = mapper.select(null); - System.out.println(select);
- Goods goods = mapper.selectByPrimaryKey(19);
- System.out.println(goods);
- session.close();
- }
自定义条件查询:
- @Test
- public void testSelectByExample(){
- Example example = new Example(Goods.class);
-
- example.createCriteria().andBetween("goodsId",15,19);
- example.or(example.createCriteria().andLike("goodsName","%茶%"));
- example.setOrderByClause("goodsId desc");
-
- IGoodsDaoCo mapper = session.getMapper(IGoodsDaoCo.class);
- mapper.selectByExample(example).forEach(System.out::println);
- }

①表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如 UserInfo 默认对应的表名为 user_info;
②表名可以使用 @Table(name = "tableName")进行指定,对不符合第一条默认规则的通过这种方式指定表名;
③字段默认和 @Column 一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式;
④可以使用 @Column(name = "filedName") 指定不符合第三条规则的表名;
⑤使用 @Transient 注解可以忽略字段,添加该注解的字段不会作为表字段使用;
⑥建议有一个 @Id 注解作为主键字段,可以有多个 @Id 注解的字段作为联合主键;
⑦如果是MySQL的自增字段,加上 @GeneratedValue(generator = "JDBC" )即可;
⑧实体里不i安逸使用基本数据类型如int类型默认是为0且无法消除。
通过逆向工程插件(代码生成工具),根据数据库中的表,自动生成Java代码类。
MyBatis Generator Core – Introduction to MyBatis Generator
- <dependency>
- <groupId>org.mybatis.generatorgroupId>
- <artifactId>mybatis-generator-coreartifactId>
- <version>1.3.2version>
- dependency>
- "1.0" encoding="UTF-8"?>
- generatorConfiguration
- PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
- "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
- <generatorConfiguration>
- <context id="testTables" targetRuntime="MyBatis3">
-
- <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
- <commentGenerator>
-
- <property name="suppressAllComments" value="false" />
- commentGenerator>
-
- <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
- connectionURL="jdbc:mysql://localhost:3306/lay-first?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai" userId="root"
- password="123456">
- jdbcConnection>
-
- <javaTypeResolver>
- <property name="forceBigDecimals" value="false" />
- javaTypeResolver>
-
- <javaModelGenerator targetPackage="com.entity"
- targetProject=".\src\main\java">
-
- <property name="enableSubPackages" value="false" />
-
- <property name="trimStrings" value="true" />
- javaModelGenerator>
-
- <sqlMapGenerator targetPackage="com.mapper"
- targetProject=".\src\main\resources">
-
- <property name="enableSubPackages" value="false" />
- sqlMapGenerator>
-
- <javaClientGenerator type="XMLMAPPER"
- targetPackage="com.mapper"
- targetProject=".\src\main\java">
-
- <property name="enableSubPackages" value="false" />
- javaClientGenerator>
-
- <table schema="" tableName="tb_goods" enableCountByExample="false" domainObjectName="Goods"
- enableUpdateByExample="false"
- enableDeleteByExample="false"
- enableSelectByExample="false"
- selectByExampleQueryId="false"
- />
- context>
- generatorConfiguration>
- @Test
- public void generator() throws Exception{
- List
warnings = new ArrayList(); - boolean overwrite = true;
- //指定 逆向工程配置文件
- File configFile = new File("E:\\Desktop\\Java_dev\\0819\\MBG\\src\\main\\resources\\mybatis-config-gen.xml");
- //配置解析器
- ConfigurationParser cp = new ConfigurationParser(warnings);
- //配置对象
- Configuration config = cp.parseConfiguration(configFile);
- //回调设置
- DefaultShellCallback callback = new DefaultShellCallback(overwrite);
- //构建mybatis代码生成工具对象
- MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
- callback, warnings);
- //进行代码生成
- myBatisGenerator.generate(null);
- }