SpringBoot中集成持久层框架Mybatis

  本篇内容是基于前面博文《Eclipse中使用Mybatis Generator自动生成POJO类、mapper类等》,在此文章上进行开发的,请注意!

完整目录结构如下:


 一、由于我已经通过Mybatis Generator插件自动生成了一些类和配置,所以我本篇博文内容就少了很多。

首先在pom.xml中添加SpringBoot整合Mybatis的起步依赖,然后因为要查数据库,所以需要MySQL的jdbc驱动(该驱动在父级依赖中已经存在,我们继承的父级依赖,所以不用写版本)

<!-- SpringBoot整合Mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

<!-- MySQL的jdbc驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

完整的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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.com.winson.springboot</groupId>
    <artifactId>maven-springboot</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.17.RELEASE</version>
        <relativePath />
    </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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
View Code

二、配置核心配置文件application.properties,注意:配置MyBatis的Mapper.xml文件所在位置。

#配置数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

#配置MyBatis的Mapper.xml文件所在位置:
mybatis.mapper-locations=classpath:mybatis/UserMapper.xml

补充一下:UserMapper.xml配置文件新添加一个查询所有的SQL语句。

<select id="selectAllUser" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
    </select>

完整的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="cn.com.winson.dao.UserMapper">

    <resultMap id="BaseResultMap" type="cn.com.winson.domin.User">
        <id column="t_id" jdbcType="VARCHAR" property="tId" />
        <result column="t_name" jdbcType="VARCHAR" property="tName" />
        <result column="t_age" jdbcType="INTEGER" property="tAge" />
        <result column="t_address" jdbcType="VARCHAR" property="tAddress" />
        <result column="t_sex" jdbcType="VARCHAR" property="tSex" />
    </resultMap>

    <sql id="Base_Column_List">
        t_id, t_name, t_age, t_address, t_sex
    </sql>

    <select id="selectAllUser" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
    </select>

    <select id="selectByPrimaryKey" parameterType="java.lang.String"
        resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
        where t_id = #{tId,jdbcType=VARCHAR}
    </select>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
        delete from t_user
        where t_id = #{tId,jdbcType=VARCHAR}
    </delete>

    <insert id="insert" parameterType="cn.com.winson.domin.User">
        insert into t_user (t_id,
        t_name, t_age,
        t_address, t_sex)
        values (#{tId,jdbcType=VARCHAR},
        #{tName,jdbcType=VARCHAR},
        #{tAge,jdbcType=INTEGER},
        #{tAddress,jdbcType=VARCHAR}, #{tSex,jdbcType=VARCHAR})
    </insert>

    <insert id="insertSelective" parameterType="cn.com.winson.domin.User">
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="tId != null">
                t_id,
            </if>
            <if test="tName != null">
                t_name,
            </if>
            <if test="tAge != null">
                t_age,
            </if>
            <if test="tAddress != null">
                t_address,
            </if>
            <if test="tSex != null">
                t_sex,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="tId != null">
                #{tId,jdbcType=VARCHAR},
            </if>
            <if test="tName != null">
                #{tName,jdbcType=VARCHAR},
            </if>
            <if test="tAge != null">
                #{tAge,jdbcType=INTEGER},
            </if>
            <if test="tAddress != null">
                #{tAddress,jdbcType=VARCHAR},
            </if>
            <if test="tSex != null">
                #{tSex,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

    <update id="updateByPrimaryKeySelective" parameterType="cn.com.winson.domin.User">
        update t_user
        <set>
            <if test="tName != null">
                t_name = #{tName,jdbcType=VARCHAR},
            </if>
            <if test="tAge != null">
                t_age = #{tAge,jdbcType=INTEGER},
            </if>
            <if test="tAddress != null">
                t_address = #{tAddress,jdbcType=VARCHAR},
            </if>
            <if test="tSex != null">
                t_sex = #{tSex,jdbcType=VARCHAR},
            </if>
        </set>
        where t_id = #{tId,jdbcType=VARCHAR}
    </update>

    <update id="updateByPrimaryKey" parameterType="cn.com.winson.domin.User">
        update t_user
        set
        t_name = #{tName,jdbcType=VARCHAR},
        t_age = #{tAge,jdbcType=INTEGER},
        t_address = #{tAddress,jdbcType=VARCHAR},
        t_sex =
        #{tSex,jdbcType=VARCHAR}
        where t_id = #{tId,jdbcType=VARCHAR}
    </update>

</mapper>
View Code

三、新建一个接口UserService.java,内容如下:

package cn.com.winson.service;

import java.util.List;

import cn.com.winson.domin.User;

public interface UserService {

    public List<User> getAllUser();
                            
    public User getUserById(String id);
}

四、新建UserService.java的实现类UserServiceImpl.java,在此类加上@Service注解,使之成为spring的一个bean并,注入UserMapper接口,具体内容如下:

package cn.com.winson.service.impl;

import java.util.List;

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

import cn.com.winson.dao.UserMapper;
import cn.com.winson.domin.User;
import cn.com.winson.service.UserService;

@Service
public class UserServiceImpl implements UserService{
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public List<User> getAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public User getUserById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }
    
}

五、新建一个UserController.java,接收请求并响应,具体内容如下:

package cn.com.winson.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import cn.com.winson.domin.User;
import cn.com.winson.service.UserService;


/*@RestController注解作用:返回的是json字符串,等同于@Controller+@ResponseBody两个注解的组合*/
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/allUser")
    public List<User> userList() {
        return userService.getAllUser();
    }

    @GetMapping("/allUser/{id}")
    public User getUser(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }
}

六、修改程序启动类:增加@MapperScan注解(默认属性值为mapper所在的包名,可以为数组),让程序扫描到接口类。这是一种方法,还有一种就是在接口类上加一个@Mapper注解,作用相同。这里去第一种方法,简洁。

package cn.com.winson;

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

@SpringBootApplication
/*@MapperScan注解:让程序扫描到接口类*/
@MapperScan("cn.com.winson.dao")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

七、运行程序,结果如下:


 

总结:

一 、在之前的博文中新添加了service接口和其实现类,以及controller类,在UserMapper.xml中新添加了一个查询所有的方法。

二、注意核心配置文件的配置添加。

三、注意我的项目中UserMapper.xml的位置,并没有与mapper.java接口同包。

码云地址:https://gitee.com/top_one/springboot-mybatis.git

posted @ 2018-12-08 12:42  温森  阅读(1115)  评论(0编辑  收藏  举报