SpringBoot集成Mybatis+MySQL

环境

  • Mac OS 10.13
  • Mybatis3.4 [org.mybatis.spring.boot 2.0.1]
  • MySQL 8.0.16
  • JAVA 11
  • SpringBoot 2.1.1.RELEASE

配置MySQL

1. 接入依赖

pom.xml 文件中添加一下依赖,用于接入JDBC驱动

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
</dependency>

2. 配置 aplication.properties

在该配置文件下,添加以下代码:

#设置数据库,使用com.mysql.cj.jdbc.Driver对应mysql6以上版本,com.mysql.jdbc.Driver对应mysql5一下版本
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username = 用户名
spring.datasource.password = 密码

据查找资料说:
使用com.mysql.cj.jdbc.Driver需要设置一下时区,但是貌似没有遇到这个坑。
另外的方法:据资料介绍,还可以在mybatis_config.xml文件中根据不同环境配置不同的数据库,例如以下代码:

<!--不同环境数据库源配置,默认是dev环境-->
    <environments default="dev">
        <!--开发环境-->
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"    value="jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"/>
                <property name="username" value="用户名"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
        <!--生产环境-->
        <environment id="prod">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"    value="jdbc:mysql://远程数据库服务设备ip/数据库?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"/>
                <property name="username" value="用户名"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
    </environments>

不过很不幸的是,这个配置好像无效。目前采用第一种方法,个人建议第二种,便于管理,将来有机会再查证无效的具体原因。

配置Mybatis

1.接入依赖

在 pom.xml 文件中添加一下依赖,用于接入Mybatis库

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
</dependency>

2.配置 aplication.properties

在这之前,你需要在resources文件夹下,新建mybatis-config.xml文件,用于添加mybatis的配置,本人工程中该文件的目录是resources/mybatis/config/mybatis-config.xml
另外,mybatis需要许多mapper文件,所以先创建一个mapper文件夹,以便将来能用,本人工程中该文件夹目录是resources/mybatis/mapper
然后引入配置和mapper文件:

mybatis.check-config-location=true
mybatis.config-location=classpath:mybatis/config/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

3.配置mybatis-config.xml

<configuration>
    <!--加载所有entity实体类-->
    <typeAliases>
        <package name="com.xxx.xxxx.entity"/>
    </typeAliases>
</configuration>

目前还没有对mybatis做过多的配置,而只是通过package的方式,加载所有entity实体类。(接下来要介绍的User.class就是在该entity文件夹下)

4.创建实体对象(entity)

com.xxx.xxxx.entity*文件夹中,新增User.class文件,内容如下:

package com.xxx.xxxx.entity;

import java.sql.Timestamp;
import java.util.Date;

public class User{

    private  String username;

    private  String email;

    private  String password;

    private int sex;

    private Date birthday;

    private String headPhoto;

    private String phone;

    private Timestamp createTime;



    public String getUsername(){
        return username;
    }
    public void setUsername(String username){
        this.username = username;
    }

    public String getEmail(){
        return  email;
    }
    public void setEmail(String email){
        this.email = email;
    }

    public String getPassword(){
        return password;
    }
    public void setPassword(String password){
        this.password = password;
    }

    public int getSex(){ return sex; }
    public void setSex(int sex){ this.sex = sex; }

    public Date getBirthday(){ return birthday; }
    public void setBirthday(Date birthday){ this.birthday = birthday; }

    public String getHeadPhoto(){ return headPhoto; }
    public void setHeadPhoto(String headPhoto){ this.headPhoto = headPhoto; }

    public String getPhone(){ return phone; }
    public void setPhone(String phone){ this.phone = phone; }

    public Timestamp getCreateTime(){
        return createTime;
    }
    public void setCreateTime(Timestamp createTime){
        this.createTime = createTime;
    }
}

然后创建数据库表user,表列如下:

user_id           varchar(64) PK
email             varchar(255)
username          varchar(16)
password          varchar(32)
create_time       timestamp
sex               int(11)
birthday          date
headphoto         varchar(200)
phone             varchar(20)

5.创建Respository接口

在mybatis中,我们需要实现查询,删除,更新等操作,所有的这些操作都在mapper.xml文件中实现,我们只需要给项目暴露接口函数就好了。我们把这些接口全部归类到respository文件夹下。例如,我们需要对user进行一些查询操作,你可以编写以下接口:
IUserMapper.class

import com.xxx.xxxx.entity.User;

public interface IUserMapper {

    //通过userId去获取用户信息
    public User getUserById(String userId);
}

6.接口实现Mapper.xml

我们需要实现getUserById操作。首先我们得在,mapper文件夹下创建一个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.xxx.xxx.respository.IUserMapper">
  
    <resultMap id="UserMapperResult" type="com.xxx.xxxx.entity.User">
        <result property="email" column="email"></result>
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <result property="headPhoto" column="head_photo"></result>
        <result property="phone" column="phone"></result>
        <result property="password" column="password"></result>
        <result property="createTime" column="create_time"></result>
    </resultMap>

    <select id="getUserById" resultMap="UserMapperResult">
        select * from user
        where
         user.user_id = #{userId}
    </select>
</mapper>

请留意这行<mapper namespace="com.xxx.xxxx.respository.IUserMapper">,这里直接关联到了IUserMapper,然后对应的接口函数getUserById,也在这里做了映射<select id="getUserById" resultMap="UserMapperResult">

7.暴露接口给mybatis

在接口与mapper.xml文件关联起来之前,我们要先把接口文件暴露给mybatis。而mybatis通过注解 @MapperScan 来扫描这些接口文件,在本人工程中,我们在application文件中添加了@MapperScan("com.xxx.xxxx.respository")代码,这样mybatis就会自动扫描respository文件夹下的所有接口了。
xxxApplication.class

package com.xxx.xxxx;

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

@MapperScan("com.xxx.xxxx.respository")
@SpringBootApplication

public class xxxApplication {

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

}

8.调用

在本人工程中,有一个loginController.class,里面实现了get请求,另外通过@Autowired的方式注入IUserMapper的bean。
LoginController.class

package com.xxx.xxxx.controllers.Login;
import com.xxx.xxxx.entity.User;
import com.xxx.xxxx.respository.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private IUserMapper userMapper;

    @RequestMapping(value = "/get" , method = RequestMethod.GET)
    public  User loginGet(){
        System.out.println("get 方法=====");
        User user = userMapper.getUserById("32435cdsg");
        return user;
    }
}

9.结果如下

{
"username":"xxxxxx",
"email":"xxx@email.com",
"password":"xxxxx","sex":0,
"birthday":null,
"headPhoto":null,
"phone":null,
"createTime":"2019-07-11T22:27:59.000+0000"
}

10.Referrence

Mybatis中文网

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270