原创

springBoot整合mybatis

配置Maven依赖

下面贴出本次整合的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.example</groupId>
    <artifactId>demo-1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-1</name>
    <description>Demo project for Spring Boot</description>


    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <name>aliyun-repos</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-plugin</id>
            <name>aliyun-plugin</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.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>
    </properties>

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

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

            <!-- 添加JSON依赖 fastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <!-- 添加JDBC依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- 添加Mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- mysql依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 阿里巴巴数据库 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>


    </dependencies>

    <build>

        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <configurationFile>src/main/resources/generator.xml</configurationFile>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.2</version>
                        </dependency>
                    </dependencies>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <skipTests>true</skipTests>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.1</version>
                    <configuration>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>



    </build>


</project>

下面这部分就是新添加的依赖了,有兴趣可以看一下罗
file

创建数据库

创建测试数据库以及数据库的测试表,这部分我这里就不详细描述了,我新建了一个testdb数据库,以及新建了test_user表

字段 描述
user_id 用户ID
username 用户名
password 用户密码

配置application.yml

本人习惯用yml来代替默认的,由于考虑到我们一般开发都会有多个环境,比如测试,开发,线上,所以我将yml分为了几个,这里只是在原有的基础上新建了一个application-test.yml
下面贴出来application.yml的配置

# Server settings
server:
    port: 8081
    # HTTP请求和响应头的最大量,以字节为单位,默认值为4096字节,超过此长度的部分不予处理,一般8K。解决java.io.EOFException: null问题
    max-http-header-size: 8192
    use-forward-headers: true
    compression:
        enabled: true
        min-response-size: 1024
        mime-types: text/plain,text/css,text/xml,text/javascript,application/json,application/javascript,application/xml,application/xml+rss,application/x-javascript,application/x-httpd-php,image/jpeg,image/gif,image/png
    tomcat:
        remote-ip-header: X-Forwarded-for
        protocol-header: X-Forwarded-Proto
        port-header: X-Forwarded-Port
        uri-encoding: UTF-8
# SPRING PROFILES
spring:
    profiles:
        active: test
    application:
        name: demo-1
      # HTTP ENCODING
    servlet:
        multipart:
            max-file-size: 2MB
            max-request-size: 10MB
    http:
        encoding:
            enabled: true
            charset: UTF-8
            force: true
    messages:
        encoding: UTF-8
    jmx:
        enabled: true
        default-domain: agentservice
    resources:
        chain:
            strategy:
                content:
                    enabled: true
                    paths: /**


mybatis:
  #对应的实体类包名
  typeAliasesPackage: com.example.demo.pojo   
  #mybatis  XML文件扫描   需要在Springboot启动处  再次扫描mapper文件
  mapper-locations: classpath:mapper/*.xml

接下来是application-test.yml,这里主要是数据库的配置

# Server settings
server:
    tomcat:
        basedir: /var/tmp/website-blog-web
# SPRING PROFILES
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
        username: root
        password: admin
    # 指定默认MimeMessage的编码,默认为: UTF-8

使用mybatis generator 自动生成代码

在src/main/resources下新建一个文件generator.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>

    <properties resource="application.yml" />
    <!-- mysql驱动的位置 这个是MySQL连接的jar包,你需要指定你自己计算机上的jar包的位置-->
    <classPathEntry location="D:\JAVA开发相关\lib\mysql-connector-java-5.1.28-bin.jar" />

    <context id="Tables" targetRuntime="MyBatis3">

        <!-- 注释 -->
        <commentGenerator>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- JDBC连接 其中connectionURL后面的testdb改为你创建的数据库,紧跟在后面是数据库连接的账户和密码-->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/testdb"
                userId="root"
                password="admin">
        </jdbcConnection>

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
         NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 生成实体类地址 这里需要你改动,其中targetPackage需要根据你自己创建的目录进行改动 -->
        <javaModelGenerator targetPackage="com.example.demo.pojo" targetProject="src/main/java">
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaModelGenerator>

        <!-- 生成mapper xml文件 这里不需要改动 -->
        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 生成mapper xml对应Client   这里需要改动targetPackage,依据你自己的工程-->
        <javaClientGenerator targetPackage="com.example.demo.mapper" targetProject="src/main/java" type="XMLMAPPER">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
            是否生成 example类 -->

        <table schema="testdb" tableName="test_user"
               domainObjectName="User" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false">
        </table>


    </context>
</generatorConfiguration>

注意要先新建指定的目录,

file

配置完成后,右键项目 --> Run as--> Maven build --> Goals: mybatis-generator:generate,点击 run.....(eclipse开发)

file

执行成功后再对应的目录下会产生相应的文件(注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记 )

file

贴出生成的代码UserMapper.java

package com.example.demo.mapper;


import com.example.demo.pojo.User;

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);
}

User.java

package com.example.demo.pojo;

public class User {
    private Integer userId;

    private String username;

    private String password;

    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();
    }
}

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="com.example.demo.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    user_id, username, password
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from test_user
    where user_id = #{userId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from test_user
    where user_id = #{userId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.demo.pojo.User" >
    insert into test_user (user_id, username, password
      )
    values (#{userId,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.pojo.User" >
    insert into test_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        user_id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </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>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.pojo.User" >
    update test_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.pojo.User" >
    update test_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
</mapper>

这边我一直有一个疑问,就是如果数据库字段有修改的话,我们重新执行这个逆向工程的话,之前我们在UserMapper.xml中自己写的方法就会被覆盖掉,这是一个很麻烦的事情,所以这边想到的一个解决办法是,自动生成的自己写的xml分成两个,自己新建一个BaseUserMapper来继承UserMapper,这样的话,就算重新生成也不会影响我自己写的方法,如果字段有更新的话,就需要自己在对应的BaseUserMapper.xml添加,这点也是不是很方便,感觉这个无法避免的
下面贴出BaseUserMapper.java以及BaseUserMapper.xml

package com.example.demo.mapper;

import java.util.List;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;

public interface BaseUserMapper extends UserMapper{

    List<User> findAllUser();
}
<?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.example.demo.mapper.BaseUserMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>

 <select id="findAllUser" resultMap="BaseResultMap">
 select * from test_user
 </select>

</mapper>

这样我们自己新加的方法就可以写在这个新建的BaseUserMapper.java以及BaseUserMapper.xml,完美

测试

在之前的Controller中添加下面的方法
TestController.java

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;

@RestController
public class TestController {

    @Autowired
    private UserService userService;

    @RequestMapping("/hello")
    public String test() {
        return "hello,springBoot";
    }

    @RequestMapping("/findUserById")
    public String findUserById() {
        User user=userService.findUserById();
        return  JSON.toJSONString(user)    ;    
    }

    @RequestMapping("/findAllUser")
    public String findAllUser() {
        List<User> user=userService.findAllUser();
        return  JSON.toJSONString(user)    ;    
    }

}

UserService.java

package com.example.demo.service;

import java.util.List;

import com.example.demo.pojo.User;

public interface UserService {

    User findUserById();

    List<User> findAllUser();

}

UserServiceImpl.java

package com.example.demo.service.serviceImpl;

import java.util.List;

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

import com.example.demo.mapper.BaseUserMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Override
    public User findUserById() {
        // TODO Auto-generated method stub
        return baseUserMapper.selectByPrimaryKey(1);
    }

    @Override
    public List<User> findAllUser() {
        // TODO Auto-generated method stub
        return baseUserMapper.findAllUser();
    }


}

最后就是启动项目访问了,还有关键的一个就是加上Mapper的扫描
file

最后启动成功后访问

file

file

Over!!!!!,有任何问题都可以在文章底部评论,第一时间看到会回复

正文到此结束
Loading...