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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM