码迷,mamicode.com
首页 > 移动开发 > 详细

spring-boot集成PageHelper和通用Mapper

时间:2018-01-30 17:05:25      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:generate   config   cat   pass   selectall   gen   XML   条件   id自增   

前提条件:已经集成mybatis

代码生成步骤:

  1. 添加依赖
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>1.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.6</version>
    </dependency>
  2. 创建一个拥有main方法的类,代码如下
    package com.ghaien.generator;
    
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.internal.DefaultShellCallback;
    import sun.nio.cs.Surrogate.Generator;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class GeneratorMain {
        /**
         * 代码生成器
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
            List<String> warnings = new ArrayList<>();
            boolean overwrite = true;
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(
                      Generator.class.getResourceAsStream("/generator/generatorConfig.xml"));
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        }
    }
  3. 在上面代码中对应的目录下创建generatorConfig.xml配置文件
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
        <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
    
            <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
                <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
                <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
                <property name="caseSensitive" value="true"/>
            </plugin>
    
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/test"
                            userId="root"
                            password="1234">
            </jdbcConnection>
            <!--生成的实体类的存储路径和包名-->
            <javaModelGenerator targetPackage="com.ghaien.dao.pojo.vo" 
    targetProject
    ="E:\document\IdeaProjects\spring-boot-demo\src\main\java"/> <!--生成的*Mapper.xml文件的存储位置--> <sqlMapGenerator targetPackage="mapper"
    targetProject
    ="E:\document\IdeaProjects\spring-boot-demo\src\main\resources"/> <!--生成的*Mapper.java文件的存储位置和包名--> <javaClientGenerator targetPackage="com.ghaien.dao.mapper"
    targetProject
    ="E:\document\IdeaProjects\spring-boot-demo\src\main\java" type="XMLMAPPER" /> <!--对应数据库中表名(可以使用"%" 对应所有表)--> <table tableName="user" > <!--该表有一个id自增的主键,在生成实体类的时候会根据该配置生成相应的注解--> <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> </context> </generatorConfiguration>

    以上配置可根据具体的需求进行配置

  4. 执行main方法

集成步骤:

  1. 添加依赖
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>1.1.4</version>
    </dependency>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.1</version>
    </dependency>
  2. application.properties中增加如下配置
    ##mapper
    ##mappers 多个接口时逗号隔开
    mapper.mappers=com.ghaien.utils.mapper.BaseMapper
    mapper.not-empty=false
    mapper.identity=MYSQL
    #
    ##pagehelper
    pagehelper.helperDialect=mysql
    pagehelper.reasonable=true
    pagehelper.supportMethodsArguments=true
    pagehelper.params=count=countSql
  3. 将生成的*Mapper.xml文件移动到application.properties中mybatis.mapperLocations对用的目录下,随意移动生成的实体类位置
  4. 创建BaseMapper(命名随意)接口,位置跟配置文件中的mapper.mappers对应,代码如下
    package com.ghaien.utils.mapper;
    
    import tk.mybatis.mapper.common.Mapper;
    import tk.mybatis.mapper.common.MySqlMapper;
    
    public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
    }

    修改生成的*Mapper.java文件,使其继承BaseMapper,并移动到@MapperScan能扫描到的路径下,代码如下

    package com.ghaien.dao.mapper;
    
    import com.ghaien.dao.pojo.vo.User;
    import org.apache.ibatis.annotations.Param;
    import tk.mybatis.mapper.common.BaseMapper;
    
    public interface UserMapper extends BaseMapper<User> {
        /**
         * 测试UserMapper.xml文件路径是否正确
         * @param id
         * @return
         */
        User queryById(@Param("id") Long id);
    }

    注意:BaseMapper不能被@MapperScan扫描到

  5. 测试是否成功集成,代码如下
    package com.ghaien.dao.mapper;
    
    import com.ghaien.dao.pojo.vo.User;
    import com.github.pagehelper.Page;
    import com.github.pagehelper.PageHelper;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.List;
    
    /**
     * Created by ghaien on 2018/1/29.
     */
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class UserMapperTest {
    
        @Autowired
        private UserMapper userMapper;
    
        private Logger log = LoggerFactory.getLogger(this.getClass());
    
        @Test
        public void testQueryByPage() {
    //        PageHelper.startPage(2, 1);
    //        List<User> users = userMapper.selectAll();
    //        for (User user : users) {
    //            log.info("userName = " + user.getUserName());
    //        }
    
            Page<User> page = PageHelper.startPage(2, 1).doSelectPage(() -> {
                userMapper.selectAll();
            });
            for (User user : page) {
                log.info("userName = " + user.getUserName());
            }
        }
    
    }

    以上两种方法最后输出的结果是一致的,若想查看sql语句只需在配置文件中增加如下配置即可

    logging.level.com.ghaien.dao=debug

完整代码

 

spring-boot集成PageHelper和通用Mapper

标签:generate   config   cat   pass   selectall   gen   XML   条件   id自增   

原文地址:https://www.cnblogs.com/guohaien/p/8384050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!