spring boot集成mybatis-generator-maven-plugin和通用mapper

时间:2023-01-14 09:02:57

                在开发中基本都是要使用数据库,编写数据库层的代码。比如我们使用mybatis,需要建立表对应的POJO类,对应的mapper接口,对应的mapperxml文件,这些都是一些繁琐的代码,一般在开发中都会考虑自动生成这些代码,利用mybatis-generator-maven-plugin插件自动生成这些代码,解放大脑和手了。但是虽然自动生成了这些代码但是对于一些单表的简单查询还是需要我们写一些sql,这时候我们可以采用通用的mapper方式,让所有的mapper继承一个通用的mapper,这样一些简单的操作就自动有了。这样我们有更多的时间休息,享受生活了。下面是mybatis-generator-maven-plugin插件和集成通用mapper示例。


 一:创建一个spring boot项目

       创建一个spring boot项目,确保项目已经集成了mybatis,参考:http://blog.csdn.net/j903829182/article/details/75643661

       

二:修改pom.xml

     在第一步的基础上,添加通用mapper包的依赖和代码自动生成的依赖,并添加相应的插件,修改完成后的pom.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.jack</groupId>
<artifactId>springbootstudy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springbootstudy</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- MyBatis Generator -->
<!-- Java接口和实体类 -->
<targetJavaProject>${basedir}/src/main/java</targetJavaProject>
<targetMapperPackage>com.jack.mapper</targetMapperPackage>
<targetModelPackage>com.jack.entity</targetModelPackage>
<!-- XML生成路径 -->
<targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
<targetXMLPackage>mapper</targetXMLPackage>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>

<!--feign方式远程调用需要的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>

<!-- 与数据库操作相关的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mybatis与springboot整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>

<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- 使用druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.1</version>
</dependency>

<!-- mybatis包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>

<!-- Mybatis Generator -->
<!-- <dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>-->
<!--集成通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<!-- 建议使用最新版本 -->
<version>3.4.2</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

<!--mybatis自动生成代码插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 自动生成的配置,${basedir}表示项目根目录 ,configurationFile默认在resource目录下-->
<!--<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>-->
</configuration>
<dependencies>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
<scope>runtime</scope>
</dependency>
<!--集成通用mapper依赖-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
</plugin>

</plugins>

</build>


</project>


三:在src/main/resources目录下创建generatorConfig.xml文件

        generatorConfig.xml文件配置了代码自动生成的一些规则和基本属性,并配置通用mapper的插件,使所有的mapper都继承通用mapper,代码如下:

<?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>
<!--配置参考地址:http://www.mybatis.org/generator/configreference/xmlconfig.html-->
<!--配置参考地址http://blog.csdn.net/pk490525/article/details/16819307-->
<!--配置参考:http://blog.csdn.net/lirui874125/article/details/49589563-->
<!--配置参考:http://www.jianshu.com/p/e09d2370b796-->


<!-- 引入配置文件 -->
<!--<properties resource="init.properties"/>-->
<!-- 指定数据连接驱动jar地址 -->
<!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->

<!--
context:生成一组对象的环境
id:必选,上下文id,用于在生成错误时提示
defaultModelType:指定生成对象的样式
1,conditional:类似hierarchical;
2,flat:所有内容(主键,blob)等全部生成在一个对象中;
3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class)
targetRuntime:
1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
introspectedColumnImpl:类全限定名,用于扩展MBG
-->

<context id="Mysql" targetRuntime="MyBatis3Simple">
<!--https://mapperhelper.github.io/docs/3.usembg/,自动生成代码的通用mapper插件-->
<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>
<!-- 注释 -->
<commentGenerator >
<!-- 是否取消自动生成的注释 -->
<!--<property name="suppressAllComments" value="false"/>-->
<!-- 是否生成注释代时间戳-->
<!-- <property name="suppressDate" value="true" />-->
</commentGenerator>

<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.9.107:3306/jack?useUnicode=true&characterEncoding=UTF8&useSSL=true"
userId="root"
password="root">
<!-- 针对mysql数据库 -->
<property name="useInformationSchema" value="true"/>
</jdbcConnection>

<!-- 类型转换 -->
<javaTypeResolver >
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}">
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<!--<property name="enableSubPackages" value="true" />-->
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<!--<property name="trimStrings" value="true" />-->
</javaModelGenerator>

<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}">
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<!-- <property name="enableSubPackages" value="true" />-->
</sqlMapGenerator>

<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator type="XMLMAPPER" targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}">
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<!--<property name="enableSubPackages" value="true" />-->
</javaClientGenerator>

<!-- 配置表信息 -->
<!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
是否生成 example类 -->
<!--<table schema="jack" tableName="ALLTYPES" domainObjectName="Customer" >-->
<!-- <property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />-->
<!-- 忽略列,不生成bean 字段 -->
<!--<ignoreColumn column="FRED" />-->
<!-- 指定列的java数据类型 -->
<!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />-->
<!-- </table>-->
<table tableName="student" domainObjectName="Student" />

</context>
</generatorConfiguration>


四:application.yml的配置如下:

 
server:  port: 9092spring:  application:    name: spring-cloud-consumer  datasource:    name: test    url: jdbc:mysql://192.168.9.107:3306/jack?characterEncoding=utf8&useSSL=true    username: root    password: root    #使用druid数据源    type: com.alibaba.druid.pool.DruidDataSource    driverClassName: com.mysql.jdbc.Driver    filters: stat    maxActive: 20    initialSize: 1    maxWait: 60000    minIdle: 1    timeBetweenEvictionRunsMillis: 60000    minEvictableIdleTimeMillis: 300000    validationQuery: select 'x'    testWhileIdle: true    testOnBorrow: false    testOnReturn: false    poolPreparedStatements: true    maxOpenPreparedStatements: 20eureka:  client:    serviceUrl:      defaultZone: http://localhost:9090/eureka/mybatis:  mapperLocations: classpath:mapper/*.xml  #指定*Mapper.xml的位置#设置日志级别,打印mybatis的日志logging:  level:    root: debug


五:修改MybatisConfig

     MybatisConfig是mybatis的配置类,代码如下:

package com.jack.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
* Created by jackc on 2017/7/20.
*/
@Configuration
public class MybatisConfig {
/**
* 注入环境变量的值
*/
@Autowired
private Environment environment;

/**
* 获取数据源DataSource
* @return
*/
@Bean
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(environment.getProperty("spring.datasource.url"));
druidDataSource.setUsername(environment.getProperty("spring.datasource.username"));
druidDataSource.setPassword(environment.getProperty("spring.datasource.password"));
druidDataSource.setDriverClassName(environment.getProperty("spring.datasource.driverClassName"));
druidDataSource.setMaxActive(Integer.parseInt(environment.getProperty("spring.datasource.maxActive")));
druidDataSource.setInitialSize(Integer.parseInt(environment.getProperty("spring.datasource.initialSize")));
druidDataSource.setMaxWait(Long.parseLong(environment.getProperty("spring.datasource.maxWait")));
druidDataSource.setMinIdle(Integer.parseInt(environment.getProperty("spring.datasource.minIdle")));
druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(environment.getProperty("spring.datasource.timeBetweenEvictionRunsMillis")));
druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(environment.getProperty("spring.datasource.minEvictableIdleTimeMillis")));
druidDataSource.setValidationQuery(environment.getProperty("spring.datasource.validationQuery"));
druidDataSource.setTestWhileIdle(Boolean.parseBoolean(environment.getProperty("spring.datasource.testWhileIdle")));
druidDataSource.setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnBorrow")));
druidDataSource.setTestOnReturn(Boolean.parseBoolean(environment.getProperty("spring.datasource.testOnReturn")));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(environment.getProperty("spring.datasource.poolPreparedStatements")));
druidDataSource.setMaxOpenPreparedStatements(Integer.parseInt(environment.getProperty("spring.datasource.maxOpenPreparedStatements")));
return druidDataSource;
}

/**
* 获取SqlSessionFactory
* @param druidDataSource
* @return
*/
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource druidDataSource) {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(druidDataSource);
bean.setTypeAliasesPackage("com.jack.entity");
LogFactory.useLog4JLogging();
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String xmlPath = environment.getProperty("mybatis.mapperLocations");
try {
bean.setMapperLocations(resolver.getResources(xmlPath));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

/**
*
* @param sqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}

/**
* 增加事务
* @param druidDataSource
* @return
*/
@Bean
public DataSourceTransactionManager transactionManager(DataSource druidDataSource) {
return new DataSourceTransactionManager(druidDataSource);
}
}


六:修改MabatisMapperScanConfig

      MabatisMapperScanConfig类是mapper的扫描类:

package com.jack.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
* Created by jack on 2017/7/20.
*/
@Configuration
//注意,由于MabatisMapperScanConfig执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MybatisConfig.class)
public class MabatisMapperScanConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
//不使用通用mapper的时候使用,org包开头的MapperScannerConfigurer扫描配置类
//MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//使用通用mapper的时候,使用tk开头的MapperScannerConfigurer扫描配置类
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//注意这里的sqlSessionFactory就是MybatisConfig里面的sqlSessionFactoryBean方法,注解bean的名字
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//接口路径,通过这些接口调用sql的配置,操作数据库
mapperScannerConfigurer.setBasePackage("com.jack.mapper");
return mapperScannerConfigurer;
}
}


注意:
 //使用通用mapper的时候,使用tk开头的MapperScannerConfigurer扫描配置类
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

MapperScannerConfigurer必须是tk开头包里面的类


七:测试

      1,创建一个student表,sql如下:

/*
Navicat MySQL Data Transfer

Source Server : MyLocalMySQL192.168.9.107
Source Server Version : 50718
Source Host : 192.168.9.107:3306
Source Database : jack

Target Server Type : MYSQL
Target Server Version : 50718
File Encoding : 65001

Date: 2017-07-24 15:06:07
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(12) DEFAULT NULL COMMENT '姓名',
`sex` tinyint(255) DEFAULT NULL COMMENT '性别,女为0,男为1',
`note` varchar(255) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;


2,进行代码自动的生成

     spring boot集成mybatis-generator-maven-plugin和通用mapper


       点击最下面的红色框的,进行代码的自动生成,如果没有问题,生成日志会输出building success。


3,查看生成的代码:

    1)生成的POJO对象Student.java,代码如下:

package com.jack.entity;

import javax.persistence.*;

public class Student {
@Id
private Integer id;

/**
* 姓名
*/
private String name;

/**
* 性别,女为0,男为1
*/
private Byte sex;

/**
* 备注
*/
private String note;

/**
* @return id
*/
public Integer getId() {
return id;
}

/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}

/**
* 获取姓名
*
* @return name - 姓名
*/
public String getName() {
return name;
}

/**
* 设置姓名
*
* @param name 姓名
*/
public void setName(String name) {
this.name = name;
}

/**
* 获取性别,女为0,男为1
*
* @return sex - 性别,女为0,男为1
*/
public Byte getSex() {
return sex;
}

/**
* 设置性别,女为0,男为1
*
* @param sex 性别,女为0,男为1
*/
public void setSex(Byte sex) {
this.sex = sex;
}

/**
* 获取备注
*
* @return note - 备注
*/
public String getNote() {
return note;
}

/**
* 设置备注
*
* @param note 备注
*/
public void setNote(String note) {
this.note = note;
}
}


2)查看生成的mapper,StudentMapper.java代码如下:

package com.jack.mapper;

import com.jack.entity.Student;
import tk.mybatis.mapper.common.Mapper;

/**
* StudentMapper集成了通用Mapper,提供了单表的基础操作
*/
public interface StudentMapper extends Mapper<Student> {
}

3)查看生成的sql配置文件,StudentMapper.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="com.jack.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.jack.entity.Student">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="TINYINT" property="sex" />
<result column="note" jdbcType="VARCHAR" property="note" />
</resultMap>
</mapper>


4)代码结构如下:

spring boot集成mybatis-generator-maven-plugin和通用mapper



4,编写一个测试的controller,StudentTestController代码如下:

package com.jack.controller;

import com.jack.entity.Student;
import com.jack.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by jack on 2017/7/24.
* 使用通用mapper进行操作
* 文档地址:https://mapperhelper.github.io/docs/
*/
@RestController
public class StudentTestController {
@Autowired
StudentMapper studentMapper;

/**
*添加学生
* @return
*/
@RequestMapping(value = "/student/add")
public String addStudent(){
Student student = new Student();
student.setName("jackmapper1");
student.setSex((byte) 0);
student.setNote("采用通用mapper和代码自动生成");
int result = studentMapper.insert(student);
if (result > 0) {
return "添加学生成功";
}else {
return "添加学生失败";
}
}

/**
* 删除学生
* @return
*/
@RequestMapping(value = "/student/delete")
public String deleteStudent(){
Student student = new Student();
student.setId(2);
int result = studentMapper.delete(student);
if (result > 0) {
return "删除学生成功";
}else {
return "删除学生失败";
}
}

/**
* 更新学生信息
* @return
*/
@RequestMapping(value = "/student/update")
public String updateStudent(){
Student student = new Student();
student.setId(3);
student.setName("nameupdate");
student.setSex((byte) 0);
student.setNote("this is update note");
int result = studentMapper.updateByPrimaryKey(student);
if (result > 0) {
return "修改学生成功";
}else {
return "修改学生失败";
}
}

/**
* 查找学生信息
* @return
*/
@RequestMapping(value = "/student/select")
public Student selectStudent(){
Student student = new Student();
student.setId(5);
Student result = studentMapper.selectByPrimaryKey(student);
return result;
}
}



5,启动spring boot项目,输入对应的url就可以进行测试了。

    通用mapper只提供了基本的单表操作的功能,如果需要负责的功能,只要在对应的mapper文件写接口,然后在对应的xml文件里面写sql就行了,然后在需要的地方调用接口,就可以使用复杂的sql操作数据库了。



项目的完整代码在github上,代码如下:https://github.com/wj903829182/springboot/tree/master/springbootstudy