MyBatis生成工具的使用:(MyBatis集成在SpringBoot中)
使用Generator生成工具之后,对于单表的CRUD操作都自动生成出来了,就不用自己去写Mapper接口、实体类、xml了。
有两种方式:
1)使用插件
2)使用代码(我们这里使用代码)Generator.java 、config.xml 来生成实体类,接口,xml配置文件。
(1)依赖
<!-- 依赖 MyBatis 核心包 -->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
</dependencies>
<!-- 控制 Maven 在构建过程中相关配置 -->
<build>
<!-- 构建过程中用到的插件 -->
<plugins>
<!-- 具体插件, 逆向工程的操作是以构建过程中插件形式出现的 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 插件的依赖 -->
<dependencies>
<!-- 逆向工程的核心依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
(2)config.xml:
用于生成实体类、sql操作接口和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>
<!---导入Spring配置文件-->
<properties resource="application.properties"/>
<!---Mybatis上下文-->
<context id="MySqlContext" defaultModelType="hierarchical" targetRuntime="MyBatis3Simple">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是;false:否 -->
<property name="suppressAllComments" value="true" />
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--配置数据库的链接信息-->
<jdbcConnection driverClass="${spring.datasource.driver-class-name}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}"/>
<!--实体类生成信息-->
<javaModelGenerator targetProject="SpringLast/src/test/java"
targetPackage="com.glp.model">
<!-- enableSubPackages:是否让 schema 作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--mybatis 的xml文件地址-->
<sqlMapGenerator targetProject="SpringLast/src/test/resources"
targetPackage="mapper">
<!-- enableSubPackages:是否让 schema 作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--mybatis的mapper接口-->
<javaClientGenerator targetProject="SpringLast/src/test/java" type="XMLMAPPER"
targetPackage="com.glp.mapper">
<!-- enableSubPackages:是否让 schema 作为包的后缀 -->
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--要生成的表结构-->
<table tableName="articles" >
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
<columnOverride column="title" javaType="java.lang.String" jdbcType="VARCHAR" />
</table>
<table tableName="users">
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
</context>
</generatorConfiguration>
(3)Generator.java:
用于加载config.xml文件,生成MyBatis文件(接口类,实体类,xml)。
package com.glp.tool;
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 java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Generator {
private static final boolean OVERWRITE = true;
private static final String CONFIG_PATH = "generator/config.xml";
public static void main(String[] args) throws Exception {
System.out.println("--------------------start generator-------------------");
List<String> warnings = new ArrayList<>();
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(CONFIG_PATH);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
DefaultShellCallback callback = new DefaultShellCallback(OVERWRITE);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
warnings.forEach(System.err::println);
System.out.println("--------------------end generator-------------------");
}
}
运行generator后,在test文件夹
中生成接口类,实体类和表结构xml:
或者执行逆向生成操作的Maven 命令,也可以同样生成上述目录:
mybatis-pgenerator:generate
将生成的实体类、接口、xml文件转移到src/main/java/com/glp
下:
(4)实体类:
Articles:
package com.glp.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
@Getter
@Setter
@ToString
public class Articles {
private Integer id;
private String coverImage;
private Integer authorId;
private String title;
private String body;
private Date publishedAt;
private Users user;
}
Users:
package com.glp.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
@Getter
@Setter
@ToString
public class Users {
private Integer id;
private String username;
private String password;
private String nickname;
private String brief;
private Date registeredAt;
}
(1)application.properties:
先用Spring配置数据库连接信息
debug=true
# 设置打印日志的级别,及打印sql语句
logging.level.root=INFO
logging.level.druid.sql.Statement=ERROR
#frank改成自己项目包的根路径
logging.level.com.glp=DEBUG
#springmvc配置参数
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#配置数据库连接池初始化参数
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/java20_blog04
spring.datasource.username=root
spring.datasource.password=mysql
#指明mapper.xml文件在哪里
mybatis.mapper-locations=classpath:mapper/**.xml
注意:
mybatis.mapper-locations=classpath:mapper/**.xml
指明mapper.xml文件在哪里.
(8)启动类:
package com.glp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.glp.mapper")//查找接口路径
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
注意:
@MapperScan(basePackages = “com.glp.mapper”)用于扫描接口所在的类,接口上有@Mapper
注解的会通过Mybatis框架生成代理类。
(5)接口:
ArticlesMapper.java
package com.glp.mapper;
import com.glp.model.Articles;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ArticlesMapper {
int deleteByPrimaryKey(Integer id);
int insert(Articles record);
Articles selectByPrimaryKey(Integer id);
List<Articles> selectAll();
int updateByPrimaryKey(Articles record);
List<Articles> queryByUserId(Integer userId);
}
UsersMapper.java
package com.glp.mapper;
import com.glp.model.Users;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UsersMapper {
int deleteByPrimaryKey(Integer id);
int insert(Users record);
Users selectByPrimaryKey(Integer id);
List<Users> selectAll();
int updateByPrimaryKey(Users record);
}
注意:
每一个接口类都要加上Mapper注解,才会让Mybatis框架扫描到该接口,进而生成Mybatis代理类。
(7)编写Controller层和service层:
1)ArticlesController.java:
package com.glp.Controller;
import com.glp.model.Articles;
import com.glp.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ArticlesController {
@Autowired
private ArticlesService articlesService;
@RequestMapping("/query/{id}")
public Object queryById(@PathVariable("id") Integer id){
Articles article = articlesService.queryById(id);
return article;
}
@RequestMapping("/queryByUserId")
public Object queryByUserId(Integer userId){
List<Articles> articlesList=articlesService.queryByUserId(userId);
return articlesList;
}
}
2)ArticlesService.java
package com.glp.service;
import com.glp.mapper.ArticlesMapper;
import com.glp.model.Articles;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class ArticlesService {
@Resource
private ArticlesMapper articlesMapper;
public Articles queryById(Integer id) {
return articlesMapper.selectByPrimaryKey(id);
}
public List<Articles> queryByUserId(Integer userId) {
return articlesMapper.queryByUserId(userId);
}
}
注意:
在这里ArticlesMapper
是一个接口,而我们可以直接去使用接口中的方法,是因为该接口上有@Mapper注解,通过Mybatis框架扫描后生成了该接口的代理类,所以我们直接使用的其实是该接口的代理类。
(6)sql语句xml配置文件
在xml文件中的命名空间namespace
中加入接口类的全类名,那么接口类就可以通过命名空间找到对应的xml.
ArticlesMapper.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.glp.mapper.ArticlesMapper">
<resultMap id="BaseResultMap" type="com.glp.model.Articles">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="cover_image" jdbcType="VARCHAR" property="coverImage" />
<result column="author_id" jdbcType="INTEGER" property="authorId" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="body" jdbcType="VARCHAR" property="body" />
<result column="published_at" jdbcType="TIMESTAMP" property="publishedAt" />
<association property="user" resultMap="com.glp.mapper.UsersMapper.BaseResultMap" columnPrefix="prefix_users_"/>
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from articles
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.glp.model.Articles">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into articles (cover_image, author_id, title,
body, published_at)
values (#{coverImage,jdbcType=VARCHAR}, #{authorId,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR},
#{body,jdbcType=VARCHAR}, #{publishedAt,jdbcType=TIMESTAMP})
</insert>
<update id="updateByPrimaryKey" parameterType="com.glp.model.Articles">
update articles
set cover_image = #{coverImage,jdbcType=VARCHAR},
author_id = #{authorId,jdbcType=INTEGER},
title = #{title,jdbcType=VARCHAR},
body = #{body,jdbcType=VARCHAR},
published_at = #{publishedAt,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select a.id, a.cover_image, a.author_id, a.title, a.body, a.published_at, u.id prefix_users_id, u.nickname prefix_users_nickname,
u.brief prefix_users_brief
from articles a join users u on a.author_id = u.id
where a.id = #{id,jdbcType=INTEGER}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select id, cover_image, author_id, title, body, published_at
from articles
</select>
<select id="queryByUserId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select id, cover_image, author_id, title, body, published_at
from articles
where author_id = #{id,jdbcType=INTEGER}
</select>
</mapper>
- 以上sql内容都是Mybatis框架自动生成的,当然也可以人工定义。
resultMap
里面是查询结果集的映射。<resultMap id="BaseResultMap" type="com.glp.model.Articles">
这里是映射到了com.glp.model.Articles中。parameterType="java.lang.Integer"
指的是传递参数的类型,author_id =
#{id,jdbcType=INTEGER} 为占位符,参数传递过来后将占位符替换掉。- 使用
resultMap="BaseResultMap"
如果结果集返回一个集合,也会自动包装成多个类。
UsersMapper.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.glp.mapper.UsersMapper">
<resultMap id="BaseResultMap" type="com.glp.model.Users">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="CHAR" property="password" />
<result column="nickname" jdbcType="CHAR" property="nickname" />
<result column="brief" jdbcType="VARCHAR" property="brief" />
<result column="registered_at" jdbcType="TIMESTAMP" property="registeredAt" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from users
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.glp.model.Users">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into users (username, password, nickname,
brief, registered_at)
values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=CHAR}, #{nickname,jdbcType=CHAR},
#{brief,jdbcType=VARCHAR}, #{registeredAt,jdbcType=TIMESTAMP})
</insert>
<update id="updateByPrimaryKey" parameterType="com.glp.model.Users">
update users
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=CHAR},
nickname = #{nickname,jdbcType=CHAR},
brief = #{brief,jdbcType=VARCHAR},
registered_at = #{registeredAt,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select id, username, password, nickname, brief, registered_at
from users
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select id, username, password, nickname, brief, registered_at
from users
</select>
</mapper>
(9)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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
</parent>
<groupId>com.glp</groupId>
<artifactId>SpringLast</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- 父项目spring-boot-starter-parent中已经配置了这两个属性,并加入到插件,所以不用配 -->
<!-- <java.version>1.8</java.version>-->
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>-->
<mysql.version>5.1.47</mysql.version>
</properties>
<dependencies>
<!-- spring-boot-starter-web: 基于SpringBoot开发的依赖包,
会再次依赖spring-framework中基本依赖包,aop相关依赖包,web相关依赖包,
还会引入其他如json,tomcat,validation等依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis-spring-boot-starter: Mybatis框架在SpringBoot中集成的依赖包,
Mybatis是一种数据库对象关系映射Object-Relationl Mapping(ORM)框架,
其他还有如Hibernate等 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--<!– Mybatis代码生成工具:生成xml文件,实体类,接口 ->-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!--druid-spring-boot-starter: 阿里Druid数据库连接池,同样的运行时需要-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<!-- mysql-connector-java: mysql数据库驱动包
在编译时没有直接使用,但是运行时需要,所以使用
scope runtime -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<!-- spring-boot-devtools: SpringBoot的热部署依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok: 简化bean代码的框架 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- spring-boot-starter-test: SpringBoot测试框架 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<!-- SpringBoot的maven打包插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>