SpringBoot 框架整合 (二) : MyBatis + Mapper + mybatis-generator

来源:互联网 发布:nginx版本1.13 编辑:程序博客网 时间:2024/06/07 00:09

[TOC]
本文实例需要用Spring Tool Suite创建基本spring boot项目,具体步骤请移步到:
SpringBoot 实战 (一) :如何创建SpringBoot项目 –入门篇

Mapper介绍

前言

使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapper文件来完成持久化DAO层(mybatis内部使用的是动态代理,所以我们不需要自己编写实现类 ),不需要实现dao的实现层,系统会自动根据方法名在映射文件中找对应的sql。。

然而在实际开发中,单表操作非常多,如果你也想像JPA、JDBC那样做一个所谓的BaseDao。那么可以实现一个通用Mapper来达到目的。现在有现成的通用Mapper插件,我们无需重新创造轮子(代码是开源的,你也可以自己在其基础上修改)。

使用通用Mapper插件

插件代码在tk.mybatis.mapper.generator包下面,一共有如下两个类:

MapperCommentGenerator:该类用于生成数据库备注字段的注释,以及实体类字段的注解。
MapperPlugin:插件的实现类,该类默认使用上面这个注释生成器,插件屏蔽了一般的CRUD方法(保留了Example),插件可以生成实体的@Table注解。

在Maven中配置(pom.xml):

<dependency>            <groupId>tk.mybatis</groupId>            <artifactId>mapper-spring-boot-starter</artifactId>            <version>1.1.1</version>        </dependency>

Mapper接口

先定义一个公用的接口类MyMapper.java:

package com.ailianshuo.mybatisxml.utility;import tk.mybatis.mapper.common.Mapper;import tk.mybatis.mapper.common.MySqlMapper;/** *  * @author ailianshuo * @date 2017年9月2日 * @param <T> */public interface MyMapper<T> extends Mapper<T>,MySqlMapper<T> {}

项目里所有实体接口都实现公共接口。例如:

public interface UserMapper extends MyMapper<User> {}

一旦继承了Mapper,继承的Mapper就拥有了以下通用的方法:

//根据实体类不为null的字段进行查询,条件全部使用=号and条件
List select(T record);

//根据实体类不为null的字段查询总数,条件全部使用=号and条件
int selectCount(T record);

//根据主键进行查询,必须保证结果唯一
//单个字段做主键时,可以直接写主键的值
//联合主键时,key可以是实体类,也可以是Map
T selectByPrimaryKey(Object key);

//插入一条数据
//支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
//优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长
int insert(T record);

//插入一条数据,只插入不为null的字段,不会影响有默认值的字段
//支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动> 回写)
//优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长
int insertSelective(T record);

//根据实体类中字段不为null的条件进行删除,条件全部使用=号and条件
int delete(T key);

//通过主键进行删除,这里最多只会删除一条数据
//单个字段做主键时,可以直接写主键的值
//联合主键时,key可以是实体类,也可以是Map
int deleteByPrimaryKey(Object key);

//根据主键进行更新,这里最多只会更新一条数据
//参数为实体类
int updateByPrimaryKey(T record);

//根据主键进行更新
//只会更新不是null的数据
int updateByPrimaryKeySelective(T record);

接口定义有以下特点:

Mapper 接口方法名和 **Mapper.xml 中定义的每个 sql 的 id 同名。
Mapper 接口方法的输入参数类型和 **Mapper.xml 中定义的 sql 的parameterType 类型相同。
Mapper 接口的返回类型和 **Mapper.xml 中定义的 sql 的 resultType 类型相同

配置application.properties

mapper.plugin = tk.mybatis.mapper.generator.MapperPluginmapper.Mapper = tk.mybatis.mapper.common.Mappermybatis.type-aliases-package=com.study.model#分模块放mybatis.mapper-locations=classpath:mapper/*/*.xmlmapper.mappers=com.ailianshuo.mybatisxml.utility.MyMappermapper.not-empty=falsemapper.identity=MYSQL

整合Mybatis-

配置

pom.xml

        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>1.3.1</version>        </dependency>        <!--这里使用mysql-->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <scope>runtime</scope>        </dependency>

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=1111

实体类

泛型(实体类)的类型必须符合要求
实体类按照如下规则和数据库表进行转换,注解全部是JPA中的注解:

  1. 表名默认使用类名,驼峰转下划线,如UserInfo默认对应的表名为user_info.
  2. 表名可以使用@Table(name = “tableName”)进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.
  3. 字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.
  4. 可以使用@Column(name = “fieldName”)指定不符合第3条规则的字段名
  5. 使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用.
  6. 建议一定是有一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键.
  7. 默认情况下,实体类中如果不存在包含@Id注解的字段,所有的字段都会作为主键字段进行使用(这种效率极低).
  8. 实体类可以继承使用,可以参考测试代码中的com.github.abel533.model.UserLogin2类.
  9. 由于基本类型,如int作为实体类字段时会有默认值0,而且无法消除,所以实体类中建议不要使用基本类型.

这三种方式不能同时使用,同时存在时按照 序列>UUID>主键自增的优先级进行选择.下面是具体配置方法:

  1. 使用序列可以添加如下的注解:
//可以用于数字类型,字符串类型(需数据库支持自动转型)的字段@SequenceGenerator(name="Any",sequenceName="seq_userid")@Idprivate Integer id;
  1. 使用UUID时:
//可以用于任意字符串类型长度超过32位的字段@GeneratedValue(generator = "UUID")private String countryname;
  1. 使用主键自增:
//不限于@Id注解的字段,但是一个实体类中只能存在一个(继承关系中也只能存在一个)@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;

mybatis-generator自动生成代码

在pom.xml中添加plugin

<plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.2</version>                <configuration>                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>                    <overwrite>true</overwrite>                    <verbose>true</verbose>                </configuration>                <dependencies>                    <dependency>                    <groupId>mysql</groupId>                    <artifactId>mysql-connector-java</artifactId>                    <version>5.1.43</version>                    </dependency>                    <dependency>                    <groupId>tk.mybatis</groupId>                    <artifactId>mapper</artifactId>                    <version>3.4.0</version>                    </dependency>                </dependencies>            </plugin>
其中generatorConfig.xml的位置,大家根据实际情况自行调整

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="baseset"  targetRuntime="MyBatis3Simple" defaultModelType="flat">        <!-- 根据Mapper生成实体类,xml文件 -->        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">            <property name="mappers" value="com.ailianshuo.project.utility.MyMapper"/>        </plugin>        <!-- 连接字符串 -->        <jdbcConnection driverClass="com.mysql.jdbc.Driver"                            connectionURL="jdbc:mysql://localhost:3306/test"                            userId="root"                            password="1111">            </jdbcConnection>        <!-- 指定生成“entity实体类、mybatis映射xml文件、mapper接口”的具体位置 -->            <javaModelGenerator targetPackage="com.ailianshuo.mybatisxml.entity.baseset" targetProject="src/main/java" >              <property name="enableSubPackages" value="true"/>              <property name="trimStrings" value="true"/>          </javaModelGenerator>          <sqlMapGenerator targetPackage="mapper.baseset" targetProject="src/main/resources" >              <property name="enableSubPackages" value="true"/>          </sqlMapGenerator>          <javaClientGenerator targetPackage="com.ailianshuo.mybatisxml.mapper.baseset" targetProject="src/main/java"   type="XMLMAPPER" >              <property name="enableSubPackages" value="true"/>          </javaClientGenerator>          <!-- 具体要生成的表,如果有多个表,复制这一段,改下表名即可 -->        <table   tableName="baseset_user"  domainObjectName="BasesetUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">          <generatedKey column="id" sqlStatement="Mysql" identity="true"/>        </table>   </context></generatorConfiguration>

运行mybatis-generator

eclipse

如果是在eclipse 中,选择pom.xml文件,击右键先择Run AS——>Maven Build… ——>在Goals框中输入:mybatis-generator:generate

命令行

如果在命令行输入Maven命令即可,注意:一定是当前项目目录(在pom.xml这一级目录)下运行该命令:

mvn mybatis-generator:generate

即可(前提是配置了mvn)

运行结果:
这里写图片描述

这里写图片描述

测试

添加mapperscan

在SpringbootMybatisxmlApplication.java (Application.java):

package com.ailianshuo.mybatisxml;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.ailianshuo.mybatisxml.mapper")public class SpringbootMybatisxmlApplication {    public static void main(String[] args) {        SpringApplication.run(SpringbootMybatisxmlApplication.class, args);    }}

或者在Mapper接口中上面加@Mapper
这样才可以使用注解的方式调用

创建测试类

BasesetUserTest.java

package com.ailianshuo.mybatisxml.test;import java.util.List;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.ailianshuo.mybatisxml.SpringbootMybatisxmlApplication;import com.ailianshuo.mybatisxml.entity.baseset.BasesetUser;import com.ailianshuo.mybatisxml.mapper.baseset.BasesetUserMapper;@RunWith(SpringJUnit4ClassRunner. class)@SpringBootTest(classes=SpringbootMybatisxmlApplication. class)public class BasesetUserTest {    @Autowired    protected BasesetUserMapper userMapper;    @org.junit.Test    public void insert() throws Exception {        BasesetUser user = new BasesetUser();        user.setUsername("ailianshuo");        user.setPassword("ailianshuo");        user.setEnable(1);        //insert        userMapper.insert(user);        int id = user.getId();//获得自动生成的主键        //selectAll        List<BasesetUser> users = userMapper.selectAll();        for (BasesetUser _user : users) {            System.out.println(_user.getId()+":"+_user.getUsername());        } /*        //update        User user2=new User();        user2.setName("wangxiaoxiao");        user2.setId(id);        userMapper.update(user2);        //delete        userMapper.delete(id);        */    }}

执行:右击–>Run–>Juit Test:

这里写图片描述

实例项目下载

请到这里下载

原创粉丝点击