Spring Boot(三)整合Mybatis

初始准备

本文项目同样将基于Spring Boot(一)快速开始的项目继续搭建


项目结构

之前的项目结构如下图所示
这里写图片描述
本文构建项目目录结构如下图所示
其中MybatisGenerator.java是用MyBatis Generator自动生成domain,mapper,以及数据库sql映射文件
这里写图片描述


配置文件

依赖文件pom.xml

<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>cn.edu.cqu</groupId>
    <artifactId>SpringBootDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>



        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 没有该配置,devtools 不生效 -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

依赖配置文件application.yml

这里使用更简洁的yml文件配置

server:
  port: 8080

spring:
    datasource:
        name: mysql_test
        type: com.alibaba.druid.pool.DruidDataSource
        #druid相关配置
        druid:
          #监控统计拦截的filters
          filters: stat
          driver-class-name: com.mysql.jdbc.Driver
          #基本属性
          url: jdbc:mysql://127.0.0.1:3306/testdatabase?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
          username: root
          password: 123456
          #配置初始化大小/最小/最大
          initial-size: 1
          min-idle: 1
          max-active: 20
          #获取连接等待超时时间
          max-wait: 60000
          #间隔多久进行一次检测,检测需要关闭的空闲连接
          time-between-eviction-runs-millis: 60000
          #一个连接在池中最小生存的时间
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
          pool-prepared-statements: false
          max-pool-prepared-statement-per-connection-size: 20

mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: app.domain

自动生成domain,mapper,以及数据库sql映射文件

使用这个功能首先需要把domain,mapper,把resources文件夹下的mapping文件夹清空。
数据库表必须先存在,原生的mybatis不能像hibernate一样自动建表
表结构如下
这里写图片描述
然后创建MyBatis Generator配置文件mybatis-generator-config.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>    
<!-- 数据库驱动 项目里引入了就不需要写出来了,直接注释-->    
    <!--<classPathEntry  location="mysql-connector-java-5.1.25-bin.jar"/>  -->  
    <context id="DB2Tables"  targetRuntime="MyBatis3">    
        <commentGenerator>    
            <property name="suppressDate" value="true"/>    
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->    
            <property name="suppressAllComments" value="true"/>    
        </commentGenerator>    
        <!--数据库链接URL,用户名、密码 -->    
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/testdatabase" userId="root" password="123456">    
        </jdbcConnection>    
        <javaTypeResolver>    
            <property name="forceBigDecimals" value="false"/>    
        </javaTypeResolver>    
        <!-- 生成模型的包名和位置-->    
        <javaModelGenerator targetPackage="app.domain" targetProject="src/main/java">    
            <property name="enableSubPackages" value="true"/>    
            <property name="trimStrings" value="true"/>    
        </javaModelGenerator>    
        <!-- 生成映射文件的包名和位置-->    
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">    
            <property name="enableSubPackages" value="true"/>    
        </sqlMapGenerator>    
        <!-- 生成DAO的包名和位置-->    
        <javaClientGenerator type="XMLMAPPER" targetPackage="app.mapper" targetProject="src/main/java">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->    
        <table tableName="info" domainObjectName="BaseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  
    </context>    
</generatorConfiguration>    

创建java文件,之后直接运行这个main函数,domain,mapper,以及数据库sql映射文件都将自动创建出来

package app;

import org.mybatis.generator.api.ShellRunner;

public class MybatisGenerator {

    public static void main(String[] args) {
        args = new String[] { "-configfile", "src\\main\\resources\\mybatis-generator-config.xml", "-overwrite" };
        ShellRunner.main(args);

    }

}

这里列一下自动生成的代码。
BaseInfo.java

package app.domain;

public class BaseInfo {
    private Long id;

    private String info;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info == null ? null : info.trim();
    }
}

BaseInfoMapper.java

package app.mapper;

import java.util.List;

import app.domain.BaseInfo;

public interface BaseInfoMapper {
    int deleteByPrimaryKey(Long id);

    int insert(BaseInfo record);

    int insertSelective(BaseInfo record);

    BaseInfo selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(BaseInfo record);

    int updateByPrimaryKey(BaseInfo record);
    //这个是自己添加的方法
    List<BaseInfo> getByInfo(String info);
}

BaseInfoMapper.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="app.mapper.BaseInfoMapper">
  <resultMap id="BaseResultMap" type="app.domain.BaseInfo">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="info" jdbcType="VARCHAR" property="info" />
  </resultMap>
  <sql id="Base_Column_List">
    id, info
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from info
    where id = #{id,jdbcType=BIGINT}
  </select>
  <!-getByInfo这里是自己写的方法->
  <select id="getByInfo" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from info
    where info = #{info,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from info
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="app.domain.BaseInfo" useGeneratedKeys="true" keyProperty="id">
    insert into info (id, info)
    values (#{id,jdbcType=BIGINT}, #{info,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="app.domain.BaseInfo">
    insert into info
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="info != null">
        info,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="info != null">
        #{info,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="app.domain.BaseInfo">
    update info
    <set>
      <if test="info != null">
        info = #{info,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="app.domain.BaseInfo">
    update info
    set info = #{info,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

Service接口和Service实现

Service接口

package app.service;

import java.util.List;

import app.domain.BaseInfo;




public interface SampleService {
    public void addInfo(BaseInfo baseInfo);
    public List<BaseInfo> getByInfo(String info);
}

Service实现

package app.service.Imp;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import app.domain.BaseInfo;
import app.mapper.BaseInfoMapper;
import app.service.SampleService;


@Service
public class SampleServiceImp  implements SampleService{
    @Autowired
    private BaseInfoMapper baseInfoMapper;

    @Override
    @Transactional
    public void addInfo(BaseInfo baseInfo) {
        baseInfoMapper.insert(baseInfo);

    }

    @Override
    @Transactional
    public List<BaseInfo> getByInfo(String info) {
        List<BaseInfo> listInfos = baseInfoMapper.getByInfo(info);
        return listInfos;
    }







}

Controller

SampleController在上一篇文章中已有,本文主要是使用InfoController 的功能,代码与第二篇是一样的

package app.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import app.domain.BaseInfo;
import app.mapper.BaseInfoMapper;
import app.service.SampleService;

@RestController
@EnableAutoConfiguration
public class InfoController {
    @Autowired
    private SampleService sampleService;

    @RequestMapping("/addInfo")
    public BaseInfo addInfo(@RequestParam(value = "info")String info) {
        BaseInfo bInfo = new BaseInfo();
        bInfo.setInfo(info);
        sampleService.addInfo(bInfo);
        return bInfo;
    }
    @RequestMapping("/getInfo")
    public List<BaseInfo> getInfo(@RequestParam(value = "info")String info) {
        List<BaseInfo> aBaseInfos = sampleService.getByInfo(info);
        return aBaseInfos;
    }
}

Application启动应用

这里需要加入@MapperScan(“app.mapper”)

package app;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("app.mapper")
public class Application {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        SpringApplication.run(Application.class, args);
    }
}

在这个java文件中右键 Run as -> Java Application。当看到 “FrameworkServlet ‘dispatcherServlet’: initialization completed in xx ms” 字样说明启动成功。
打开浏览器访问 http://localhost:8080/addInfo?info=abc,结果如下:
这里写图片描述
之后访问http://localhost:8080/getInfo?info=abc可以看到数据已经查询到了
这里写图片描述

项目可在GitHub上下载https://github.com/tripleHu/SpringBootDemo


项目可能会遇到的问题

  1. 项目启动时出现org.springframework.beans.factory.UnsatisfiedDependencyException异常,一般情况是无法注入mapper,可以先检查一遍pom.xml中引入的包的版本之间是否兼容
  2. 有主键id为自动增长的表可以在插入时设置useGeneratedKeys=”true” keyProperty=”id”,可以参照本文中的mapper配置文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值