一:项目结构:

:pom文件如下:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent> <dependencies>
<!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- jdbcTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <!-- MySQL连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Add typical dependencies for a web application -->
<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>

三:数据库配置:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.1.20:3306/test
username: root
password: root123

四:代码说明:

最开始使用mybati比较麻烦,各种配置文件、实体类、dao层映射关联、还有一大推其它配置。当然mybatis也发现了这种弊端,初期开发了generator可以根据表结果自动生产实体类、配置文件和dao层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了。

于是两种使用方式都介绍一下,一、无配置注解版 二、配置文件版

1.无配置文件注解版
加入配置文件
————————————————

实体类User.class

package cn.saytime.bean;

import java.util.Date;

/**
* @ClassName cn.saytime.bean.User
* @Description
* @date 2017-07-04 22:47:28
*/
public class User { private int id;
private String username;
private int age;
private Date ctm; public User() {
} public User(String username, int age) {
this.username = username;
this.age = age;
this.ctm = new Date();
} // Getter、Setter
package cn.saytime.mapper;

import cn.saytime.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import java.util.List; // @Mapper 这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
public interface UserMapper { @Select("SELECT * FROM tb_user WHERE id = #{id}")
User getUserById(Integer id); @Select("SELECT * FROM tb_user")
public List<User> getUserList(); @Insert("insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())")
public int add(User user); @Update("UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}")
public int update(@Param("id") Integer id, @Param("user") User user); @Delete("DELETE from tb_user where id = #{id} ")
public int delete(Integer id); ————————————————
UserService.class

package cn.saytime.service;

import cn.saytime.bean.User;
import org.springframework.stereotype.Service; import java.util.List; /**
* @ClassName cn.saytime.service.UserService
* @Description
*/
public interface UserService { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(Integer id, User user); public int delete(Integer id);
UserServiceimpl.class

package cn.saytime.service.impl;

import cn.saytime.bean.User;
import cn.saytime.mapper.UserMapper;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* @ClassName cn.saytime.service.impl.UserServiceImpl
* @Description
*/
@Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper; @Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
} @Override
public List<User> getUserList() {
return userMapper.getUserList();
} @Override
public int add(User user) {
return userMapper.add(user);
} @Override
public int update(Integer id, User user) {
return userMapper.update(id, user);
} @Override
public int delete(Integer id) {
return userMapper.delete(id);
}
}
JsonResult.class 通用json返回类:

package cn.saytime.bean;

public class JsonResult {

    private String status = null;

    private Object result = null;

    public JsonResult status(String status) {
this.status = status;
return this;
} // Getter Setter
UserController.class(Restful风格)

package cn.saytime.web;

import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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; import java.util.List; /**
* @ClassName cn.saytime.web.UserController
* @Description
* @date 2017-07-04 22:46:14
*/
@RestController
public class UserController { @Autowired
private UserService userService; /**
* 根据ID查询用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
User user = userService.getUserById(id);
r.setResult(user);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 查询用户列表
* @return
*/
@RequestMapping(value = "users", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
JsonResult r = new JsonResult();
try {
List<User> users = userService.getUserList();
r.setResult(users);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 添加用户
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<JsonResult> add (@RequestBody User user){
JsonResult r = new JsonResult();
try {
int orderId = userService.add(user);
if (orderId < 0) {
r.setResult(orderId);
r.setStatus("fail");
} else {
r.setResult(orderId);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 根据id删除用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
int ret = userService.delete(id);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 根据id修改用户信息
* @param user
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
JsonResult r = new JsonResult();
try {
int ret = userService.update(id, user);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} }
Application.java

package cn.saytime;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("cn.saytime.mapper")
public class SpringbootMybaitsApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootMybaitsApplication.class, args);
}

测试:

使用PostMan通过测试: http://localhost:8080/user/1

2.配置文件版

加入配置文件

代码部分,相比于上面那种方式,改变的只有配置文件以及下面几个部分UserMapper.class

package cn.saytime.mapper;

import cn.saytime.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository; import java.util.List; /**
* @ClassName cn.saytime.mapper.UesrMapper
* @Description
*/
@Repository
public interface UserMapper { User getUserById(Integer id); public List<User> getUserList(); public int add(User user); public int update(@Param("id") Integer id, @Param("user") User user); public int delete(Integer id); } UserServiceImpl类:

import java.util.List;

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

import org.springframework.stereotype.Service;


import com.demo.dao.UserDao;
import com.demo.mapper.User;
import com.demo.mapper.UserMapper1;
import com.demo.service.UserService;


@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserDao userDao;

@Autowired
private UserMapper1 userMapper;


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


@Override
public List<User> getUserList() {
return userMapper.getUserList();
}

}

 
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
</typeAliases>
</configuration>
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.saytime.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="cn.saytime.bean.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
</resultMap> <sql id="Base_Column_List" >
id, username, age, ctm
</sql> <select id="getUserList" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
</select> <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
WHERE id = #{id}
</select> <insert id="add" parameterType="cn.saytime.bean.User" >
INSERT INTO
tb_user
(username,age,ctm)
VALUES
(#{username}, #{age}, now())
</insert> <update id="update" parameterType="java.util.Map" >
UPDATE
tb_user
SET
username = #{user.username},age = #{user.age}
WHERE
id = #{id}
</update> <delete id="delete" parameterType="java.lang.Integer" >
DELETE FROM
tb_user
WHERE
id = #{id}
</delete>
</mapper>

测试方法同上:http://localhost:8080/user/1

五、简要说明:
不知道大家有没有注意到一点,就是引入Springboot-mybatis依赖的时候,并不是spring官方的starter,往常的springboot集成的依赖,比如web,redis等,groupId以及artifactId的地址如下:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
而这里是mybatis为spring提供的starter依赖,所以依赖地址是:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
而且值得注意的是,这里必须要指定版本号,往常我们使用springboot之所以不需要指定版本号,是因为我们引入的Maven Parent 中指定了SpringBoot的依赖,SpringBoot官方依赖Pom文件中已经指定了它自己集成的第三方依赖的版本号,对于Mybatis,Spring官方并没有提供自己的starter,所以必须跟正常的maven依赖一样,要加版本号。
————————————————

SpringBoot(五) SpringBoot整合mybatis的更多相关文章

  1. SpringBoot 2.X整合Mybatis

    1.创建工程环境 勾选Web.Mybatis.MySQL,如下 依赖如下 <dependency> <groupId>org.springframework.boot</ ...

  2. 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源

    目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...

  3. SpringBoot当中如何整合mybatis和注入

    [学习笔记] 6.整合mybatis和注入: 马克-to-win@马克java社区: 根据第3部分的helloworld例子,用那个项目做底子.pom.xml只需要加入mybatis和mysql的部分 ...

  4. springboot笔记07——整合MyBatis

    前言 Springboot 整合 MyBatis 有两种方式,分别是:"全注解版" 和 "注解.xml混合版". 创建项目 创建Springboot项目,选择依 ...

  5. springboot学习2 整合mybatis

    springboot整合mybatis 一.添加mybatis和数据库连接的依赖 <!--整合mybatis--> <dependency> <groupId>or ...

  6. SpringBoot学习之整合Mybatis

    本博客使用IDEA开发工具,通过Maven构建SpringBoot项目,初始化项目添加的依赖有:spring-boot-starter-jdbc.spring-boot-starter-web.mys ...

  7. SpringBoot | 3.2 整合MyBatis

    目录 前言 1. 导入MyBatis场景 1.1 初始化导向 1.2 手动导入 2. *MyBatis自动配置原理 3. 全局配置文件 @Mapper @MapperScan 3.1 配置模式 3.2 ...

  8. 利用IDEA搭建SpringBoot项目,整合mybatis

    一.配置文件.启动项目 生成之后这几个文件可以删掉的 配置application spring.datasource.url=jdbc:mysql://localhost:3306/test?serv ...

  9. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  10. SpringBoot学习:整合Mybatis,使用HikariCP超高性能数据源

    一.添加pom依赖jar包: <!--整合mybatis--> <dependency> <groupId>org.mybatis.spring.boot</ ...

随机推荐

  1. go语言的json

    简介 json 中提供的处理 json 的标准包是 encoding/json,主要使用的是以下两个方法: // 序列化 func Marshal(v interface{}) ([]byte, er ...

  2. Java连接数据库 #07# MyBatis Generator简单例子

    MyBatis Generator是一个可以帮助我们免去手写实体类&接口类以及XML的代码自动生成工具. 下面,通过一个简单的例子介绍MyBatis Generator如何使用. 大体流程如下 ...

  3. navicat的一些常用快捷键

    Navicat可以支持连接多种数据库,使用上的功能也比较强大. 如果使用了IDEA内置的数据库工具(个人喜欢用这个)或是SQL Server官方的数据库管理工具的话,会发现使用上都存在区别,区别就主要 ...

  4. NFS深度解析及搭建同步NFS服务

    1.nfs 进程 [root@nfsserver ~]# ps -ef|egrep "nfs|rpc" rpcuser : ? :: rpc.statd -->检查文件一致性 ...

  5. (转)颜色直方图, HSV直方图, histogram bins

    原文链接:https://www.xuebuyuan.com/3256564.html 一个histogram,通常可以用一个列向量表示(例子中的a,b),列向量里面的每一个值就是一个bin(a,b) ...

  6. 资深程序员告诉你为什么要用Python3而不是Python2

    经常遇到这样的问题:<现在开始学习python的话,是学习python2.x还是学习python3.x比较好?>,这也是许多初学者会遇到的问题,我们的答案是python 3.x. 为了帮助 ...

  7. JVM发生full gc的情景有哪些

    除直接调用System.gc外,触发Full GC执行的情况有如下四种.1. 旧生代空间不足 旧生代空间只有在新生代对象转入及创建为大对象.大数组时才会出现不足的现象,当执行Full GC后空间仍然不 ...

  8. SSM框架之Spring(5)JdbcTemplate及spring事务控制

    Spring(5)JdbcTemplate及spring事务控制 ##1.JdbcTmeplate 它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装.spring ...

  9. vue.js+THREE.js演示服务端3D模型流程总结

    three.js官网 ·场景搭建 使用npm或者其他获取安装three,就像npm i three,之后在需要演示模型的vue组件内import * as THREE from 'three',此时我 ...

  10. Java后端,最全知识点

    你可能有所感悟.零散的资料读了很多,但是很难有提升.到处是干货,但是并没什么用,简单来说就是缺乏系统化.另外,噪音太多,雷同的框架一大把,我不至于全都要去学了吧. 这里,根据基础.Java基础.Jav ...