SpringBoot作为现在非常流行的微服务框架。

Mybatis作为现在非常流行的ORM框架。

他们整合在一起是不是会产生火花呢。

今天就搭建一个SpringBoot+Mybatis的微服务

开发环境:IEDA,JDK1.8

首先我们先创建个maven的工作空间。

左边选中Maven,右边什么都不选>>>>>>>>>>>>Next。

配置好项目信息>>>Next

上图是创建好的项目,我们只是把它作为一个工作空间,把多余的删除,我们先把src目录删了

删除之后,我们正式开始搭建SpringBoot+Mybatis

我们新建一个Module


引用web+mysql+mybatis包>>>>>>>>>>>>Next

Module命名  Next

创建完成之后我们来看看他的pom文件有什么不一样呢

<?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.spring</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.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>
        <!--  web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>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>
        </plugins>
    </build>


</project>
其实SpringBoot项目 也就是一个maven项目,你只需要把你需要用到的Jar包引入到pom文件中即可。


我们再把数据库连接配置一下吧打开我们的application.yml

#配置数据源
spring:
  datasource:
     url: jdbc:mysql://127.0.0.1:3306/studying
     username: root
     password: root
     driver-class-name: com.mysql.jdbc.Driver

#指定mybatis映射文件的地址
mybatis:
  mapper-locations: classpath:mapper/*.xml

server:
  port: 8099
这里数据库我用的是mysql本地数据库,数据库名:studying,账户:root,密码:root,大家可以根据实际情况而定。

mybatis-mapper-locations:配置的是我们映射的xml文件路径,项目启动的时候要扫描该路径下的所有XML完成映射。

server-port这就是服务的访问端口--默认写是8080。

会用到的建表语句

CREATE TABLE `s_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `userName` varchar(255) COLLATE utf8mb4_vietnamese_ci DEFAULT NULL COMMENT '用户名',
  `password` varchar(255) COLLATE utf8mb4_vietnamese_ci DEFAULT NULL COMMENT '密码',
  `email` varchar(255) COLLATE utf8mb4_vietnamese_ci DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci;

CREATE TABLE `s_orders` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '订单ID',
  `userId` bigint(20) DEFAULT NULL COMMENT '用户ID',
  `price` double(20,0) DEFAULT NULL COMMENT '价钱',
  `content` varchar(255) COLLATE utf8mb4_vietnamese_ci DEFAULT NULL COMMENT '内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci;




我们现在resources新建一个mapper路径

放置我们的xml文件

建好项目该有的model-service-dao-controller包(虽然是小demo,麻雀虽小,五脏俱全)

这里呢做两个案例,一个是合起xml使用,sql和java代码分离。一个是免xml使用。

我们建一个User类

package com.spring.mybatis.model;

/**
 * @ClassName User
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
public class User {

    private Long id;

    private String  userName;

    private String  password;

    private String  email;

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

我们就做一个添删改查的例子,项目中常见的

写一个接口实现数据的添删改查

package com.spring.mybatis.model;

/**
 * @ClassName User
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
public class User {

    private Long id;

    private String  userName;

    private String  password;

    private String  email;

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

然后再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" >
<!-- 指定dao -->
<mapper namespace="com.spring.mybatis.dao.UserDao">
    <!--  id指定方法名  parameterType指定参数类型 resultType返回参数类型 #{userName}对应User表里面的字段N要大写不然映射报错   -->
    <select id="findByUserName" parameterType="String" resultType="com.spring.mybatis.model.User">
        select id,userName,password,email from s_user where userName = #{userName}
    </select>

    <!--  id指定方法名  parameterType指定参数类型 useGeneratedKeys自动生成主键 keyProperty主键id   -->
    <insert id="insertUser" parameterType="com.spring.mybatis.model.User" useGeneratedKeys="true" keyProperty="id">
        insert into s_user(userName, password,email) VALUES(#{userName}, #{password},#{email})
    </insert>

    <delete id="deleteUserById" parameterType="Long">
        delete  from s_user where id = #{id}
    </delete>

    <update id="updatePassword" parameterType="com.spring.mybatis.model.User">
        update s_user set password = #{password} where userName = #{userName}
    </update>

</mapper>

写好我们该有的Service层

package com.spring.mybatis.service;

import com.spring.mybatis.model.User;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
public interface UserService {

    User findByUserName(String userName);

    void insertUser(User user);

    void deleteUserById(Long id);

    void updatePassword(User user);

}
再实现它的接口

package com.spring.mybatis.service.impl;

import com.spring.mybatis.dao.UserDao;
import com.spring.mybatis.model.User;
import com.spring.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUserName(String userName) {
        return userDao.findByUserName(userName);
    }

    @Override
    public void insertUser(User user) {
        userDao.insertUser(user);
    }

    @Override
    public void deleteUserById(Long id) {
        userDao.deleteUserById(id);
    }

    @Override
    public void updatePassword(User user) {
        userDao.updatePassword(user);
    }
}
写个Controller来测试一下吧

package com.spring.mybatis.controller;

import com.spring.mybatis.model.User;
import com.spring.mybatis.service.impl.UserServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    /**
     * 添加一个用户
     * @param userName
     * @param password
     * @param email
     * @return
     */
    @GetMapping(value = "/inserUser")
    @ResponseBody
    public Object inserUser(@Param("userName") String userName,@Param("password") String password,@Param("email") String email){
        Map<String,Object> data = new HashMap<>();
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setEmail(email);
        userService.insertUser(user);
        data.put("code","0");
        data.put("message","添加成功!");
        return data;
    }

    /**
     * 根据用户名查询用户
     * @param userName
     * @return
     */
    @GetMapping(value = "/findByUserName")
    @ResponseBody
    public  Object findByUserName(@Param("userName")String userName){
        Map<String,Object> data = new HashMap<>();
        User user = userService.findByUserName(userName);
        if (null != user) {
            data.put("user",user);
            data.put("code","0");
            data.put("message","查询成功!");
        } else {
            data.put("code","0");
            data.put("message","没有找到用户!");
        }
        return data;
    }

    /**
     * 根据Id删除用户
     * @param id
     * @return
     */
    @GetMapping(value = "/deleteUserById")
    @ResponseBody
    public Object deleteUserById(@Param("id")Long id){
        Map<String,Object> data = new HashMap<>();
        userService.deleteUserById(id);
        data.put("code","0");
        data.put("message","删除成功!");
        return data;
    }

    /**
     * 根据用户名更新密码
     * @param password
     * @param userName
     * @return
     */
    @GetMapping(value = "/updatePassword")
    @ResponseBody
    public Object updatePassword(@Param("password")String password,@Param("userName")String userName){
        Map<String,Object> data = new HashMap<>();
        User user = userService.findByUserName(userName);
        if (null != user) {
            user.setPassword(password);
            userService.updatePassword(user);
            data.put("user",user);
            data.put("code","0");
            data.put("message","修改成功!");
        } else {
            data.put("code","0");
            data.put("message","没有找到用户!");
        }
        return data;
    }

}


后面的我就不一一演示了。大家只要知道其中的原理就行啦。

我们再写一个免XMl配置的Orders(ps---Order是特殊字段,所以加个s)

package com.spring.mybatis.model;

/**
 * @ClassName Orders
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
public class Orders {

    private Long    id;

    private Long    userId;

    private Double price;

    private String  content;

    public Long getId() {
        return id;
    }

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

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", userId=" + userId +
                ", price=" + price +
                ", content='" + content + '\'' +
                '}';
    }
}

dao层直接写SQL

package com.spring.mybatis.dao;

import com.spring.mybatis.model.Orders;
import org.apache.ibatis.annotations.*;

/**
 * 直接在Java里面写Sql
 */
@Mapper
public interface OrdersDao {

    @Select("select id, userId, price,  content from s_orders where userId = #{userId}")
    Orders findOrdersByUserId(@Param("userId") Long userId);

    @Insert("insert into s_orders(userId, price, content) values (#{userId}, #{price}, #{content})")
    int insertOrders(@Param("userId") Long userId, @Param("price") Double price, @Param("content") String content);

    @Delete("delete from s_orders where id = #{id}")
    int deleteOrders(@Param("id") Long id);

    @Update("update s_orders set content = #{content} where userId = #{userId}")
    int updateOrders(@Param("content") String content, @Param("userId")Long userId);
}
不得不说Spring的注解功能非常强大

package com.spring.mybatis.service;

import com.spring.mybatis.model.Orders;

public interface OrdersService {

    Orders findOrdersByUserId(Long userId);

    void insertOrders(Long userId, Double price, String content);

    int deleteOrders(Long id);

    int updateOrders(String content, Long userId);

}
package com.spring.mybatis.service.impl;

import com.spring.mybatis.dao.OrdersDao;
import com.spring.mybatis.model.Orders;
import com.spring.mybatis.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName OrdersServiceImpl
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;

    @Override
    public Orders findOrdersByUserId(Long userId) {
        return ordersDao.findOrdersByUserId(userId);
    }

    /**
     * 添加事物管理--报错--代码回滚
     * @param userId
     * @param price
     * @param content
     * @return
     */
    @Override
    @Transactional
    public void insertOrders(Long userId, Double price, String content) {
        ordersDao.insertOrders(userId, price, content);
//        int max = 2/0;    //正常情况下,代码执行到这报错,但是已经走了inserOrders方法。加上事物管理,他会把inserOrders方法回滚,你把注释放开看看
    }

    @Override
    public int deleteOrders(Long id) {
        return ordersDao.deleteOrders(id);
    }

    @Override
    public int updateOrders(String content, Long userId) {
        return ordersDao.updateOrders(content, userId);
    }
}
package com.spring.mybatis.controller;

import com.spring.mybatis.model.Orders;
import com.spring.mybatis.model.User;
import com.spring.mybatis.service.impl.OrdersServiceImpl;
import com.spring.mybatis.service.impl.UserServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OrdersController
 * @Description TODO
 * @Author Tiny
 * @Date 2018/6/5
 * @Version 1.0
 */
@RestController
@RequestMapping(value = "/order")
public class OrdersController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private OrdersServiceImpl ordersService;

    /**
     *查询用户下的订单
     * @param userName 传一个userName--@Param-课直接接收前端传递过来的值,取代传统的request.getParameter();
     * @return
     */
    @GetMapping(value = "/findOrdersByUserName")
    @ResponseBody
    public Object findOrdersByUserName(@Param("userName") String userName){
        Map<String,Object> data = new HashMap<>();
        User user = userService.findByUserName(userName);
        if (null != user) {
            Orders order = ordersService.findOrdersByUserId(user.getId());
            if (null != order) {
                data.put("order", order);
                data.put("user", user);
                data.put("code", "0");
                data.put("message", "操作成功!");
            } else {
                data.put("user", user);
                data.put("code", "0");
                data.put("message", "该用户下没有订单!");
            }
        } else {
            data.put("code", "1");
            data.put("message", "用户不存在!");
        }
        return data;
    }

    /**
     * 给用户插入一条订单
     * @param userName
     * @param price
     * @param content
     * @return
     */
    @GetMapping(value = "/insertOrders")
    @ResponseBody
    public Object insertOrders(@Param("userName") String userName,@Param("price") Double price,@Param("content") String content){
        Map<String,Object> data = new HashMap<>();
        User user = userService.findByUserName(userName);
        if (null != user) {
            ordersService.insertOrders(user.getId(), price, content);
            data.put("message", "添加成功");
            data.put("code", "0");
        } else {
            data.put("code", "1");
            data.put("message", "用户不存在!");
        }
        return data;
    }

    /**
     * 删除订单
     * @param orderId
     * @return
     */
    @GetMapping(value = "/deleteOrders")
    @ResponseBody
    public Object deleteOrders(@Param("id") Long orderId){
        Map<String,Object> data = new HashMap<>();
        int count = ordersService.deleteOrders(orderId);
        data.put("count",count);
        return data;
    }

    /**
     * 更新订单数据
     * @param userName
     * @param content
     * @return
     */
    @GetMapping(value = "/updateOrders")
    @ResponseBody
    public Object updateOrders(@Param("userName")String userName, @Param("content") String content){
        Map<String,Object> data = new HashMap<>();
        User user = userService.findByUserName(userName);
        if (null != user) {
            int count = ordersService.updateOrders(content, user.getId());
            if (count > 0) {
                data.put("message", "修改成功");
                data.put("code", "0");
            }else {
                data.put("message", "修改失败");
                data.put("code", "1");
            }
        } else {
            data.put("code", "1");
            data.put("message", "用户不存在!");
        }
        return data;
    }

}
我们把两块的业务整合到一起去,看看



注释我都写代码里了

源码目前就不分享了,如果真的想要去深入了解,还是自己码一遍比较好。

后期再发一个JPA的案例,哈哈。


哪里不对的地方,请大家多多指正。


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐