springboot2整合mybatis,包括分页插件和generator

pom文件

 	    <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--mybatis generator-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

		<build>
	        <plugins>
	            <plugin>
	                <groupId>org.springframework.boot</groupId>
	                <artifactId>spring-boot-maven-plugin</artifactId>
	            </plugin>
	
	            <!--mybatis generator插件-->
	            <plugin>
	                <groupId>org.mybatis.generator</groupId>
	                <artifactId>mybatis-generator-maven-plugin</artifactId>
	                <version>1.3.7</version>
	                <configuration>
	                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
	                    <overwrite>true</overwrite>
	                    <verbose>true</verbose>
	                </configuration>
	            </plugin>
	        </plugins>
    	</build>

mainClass上加上MapperScan注解,用来扫描生成的mapper类(也就是我们常说的dao)

@SpringBootApplication
@MapperScan("head.admin.modules.sys.mapper")
public class AdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }
}

application.yml配置如下:

#注意冒号后面的空格不能省略,否则会造成不能识别
spring:
  freemarker:
    cache: false
    suffix: .html
  datasource:
    url: jdbc:mysql://ip:3306/test?useUnicode=true&characterEncoding=UTF-8
    username: xxx
    password: xxx
mybatis:
  mapper-locations: classpath:mapper/*.xml
logging:
  level:
    head.admin.modules.sys.mapper: DEBUG
pagehelper:
  reasonable: true
  support-methods-arguments: true
  params: count=countSql
  helper-dialect: mysql


generator配置文件

<?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>
    <classPathEntry
            location="D:\apache-maven-3.3.9\m2\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>
    <context id="DB2Tables" targetRuntime="mybatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://ip:3306/test"
                        userId="xxx" password="xxx"/>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="head.admin.modules.sys.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="head.admin.modules.sys.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <table catalog="head_security" tableName="t_user" domainObjectName="User" enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

注意在新版本中要设置table中的catalog="head_security"属性,否则会在生成过程中报找不到主键信息的警告。
在generator中插件中添加-e参数,用于打印异常信息。
在这里插入图片描述

建表

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `user_Id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  PRIMARY KEY (`user_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

执行generator插件的generate生命周期,会生成User.java、UserMapper.java、UserMapper.xml3个文件。

User.java

package head.admin.modules.sys.entity;

public class User {
    private Integer userId;

    private String userName;

    private String password;

    private String phone;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}

UserMapper.java

package head.admin.modules.sys.mapper;

import head.admin.modules.sys.entity.User;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> selectUsers();

}

UserMapper.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">
<mapper namespace="head.admin.modules.sys.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="head.admin.modules.sys.entity.User">
        <id column="user_Id" jdbcType="INTEGER" property="userId"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
        <result column="password" jdbcType="VARCHAR" property="password"/>
        <result column="phone" jdbcType="VARCHAR" property="phone"/>
    </resultMap>
    <sql id="Base_Column_List">
    user_Id, user_name, password, phone
  </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from t_user
        where user_Id = #{userId,jdbcType=INTEGER}
    </select>
    <select id="selectUsers" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM
        t_user
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_user
    where user_Id = #{userId,jdbcType=INTEGER}
  </delete>
    <insert id="insert" parameterType="head.admin.modules.sys.entity.User">
    insert into t_user (user_Id, user_name, password, 
      phone)
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{phone,jdbcType=VARCHAR})
  </insert>
    <insert id="insertSelective" parameterType="head.admin.modules.sys.entity.User">
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                user_Id,
            </if>
            <if test="userName != null">
                user_name,
            </if>
            <if test="password != null">
                password,
            </if>
            <if test="phone != null">
                phone,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                #{userId,jdbcType=INTEGER},
            </if>
            <if test="userName != null">
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="phone != null">
                #{phone,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="head.admin.modules.sys.entity.User">
        update t_user
        <set>
            <if test="userName != null">
                user_name = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="phone != null">
                phone = #{phone,jdbcType=VARCHAR},
            </if>
        </set>
        where user_Id = #{userId,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="head.admin.modules.sys.entity.User">
    update t_user
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR}
    where user_Id = #{userId,jdbcType=INTEGER}
  </update>
</mapper>

接着编写剩余的service、controller即可。

分页示例代码如下:

	@Override
    public PageInfo<User> selectUsers(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectUsers();
        return new PageInfo<>(users);
    }

只要传入pageNum和pageSize,传入List,返回PageInfo即可,免去了自己写分页逻辑的麻烦。返回结果示例:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值