SpringBoot整合MyBatis(转)

怎么说了,写博客虽然是一件很费时间的事情,而且还是个菜鸟,但是如果写的东西能够帮助到别人,还是值得开心的。

回顾:

上篇写了JdbcTemplate,但是想到使用Mybatis,JPA的人估计不少,所以这篇写一下SpringBoot整合Mybatis,JPA的话以后有时间再弄,因为自己也没用过。

一、数据准备

其实还是上篇的,以防有人是直接看这篇的,就还是贴出来吧。

  1. CREATE TABLE `tb_user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  3. `username` varchar(50) NOT NULL COMMENT '用户名',
  4. `age` int(11) NOT NULL COMMENT '年龄',
  5. `ctm` datetime NOT NULL COMMENT '创建时间',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8
  1. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ;
  2. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
  3. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;

二、引入依赖

  1. <!-- Spring-Mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot </groupId>
  4. <artifactId>mybatis-spring-boot-starter </artifactId>
  5. <version>1.3.0 </version>
  6. </dependency>
  7. <!-- MySQL -->
  8. <dependency>
  9. <groupId>mysql </groupId>
  10. <artifactId>mysql-connector-java </artifactId>
  11. </dependency>

另外web依赖也需要,因为我们采用MVC模式。

  1. <!-- Add typical dependencies for a web application -->
  2. <dependency>
  3. <groupId>org.springframework.boot </groupId>
  4. <artifactId>spring-boot-starter-web </artifactId>
  5. </dependency>

三、数据库配置文件

  1. spring:
  2. datasource:
  3. driver-class-name : com.mysql.jdbc.Driver
  4. url: jdbc: mysql: //localhost:3306/db_user
  5. username: root
  6. password: root

四、代码

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

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

1.无配置文件注解版

加入配置文件

  1. mybatis:
  2. type-aliases-package: cn .saytime .bean

这里写图片描述

实体类User.class

  1. package cn.saytime.bean;
  2. import java.util.Date;
  3. /**
  4. * @ClassName cn.saytime.bean.User
  5. * @Description
  6. * @date 2017-07-04 22:47:28
  7. */
  8. public class User {
  9. private int id;
  10. private String username;
  11. private int age;
  12. private Date ctm;
  13. public User() {
  14. }
  15. public User(String username, int age) {
  16. this.username = username;
  17. this.age = age;
  18. this.ctm = new Date();
  19. }
  20. // Getter、Setter
  21. }

UserMapper.class

  1. package cn.saytime.mapper;
  2. import cn.saytime.bean.User;
  3. import org.apache.ibatis.annotations.Delete;
  4. import org.apache.ibatis.annotations.Insert;
  5. import org.apache.ibatis.annotations.Param;
  6. import org.apache.ibatis.annotations.Select;
  7. import org.apache.ibatis.annotations.Update;
  8. import java.util.List;
  9. // @Mapper 这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
  10. public interface UserMapper {
  11. @Select ( "SELECT * FROM tb_user WHERE id = #{id}" )
  12. User getUserById(Integer id);
  13. @Select ( "SELECT * FROM tb_user" )
  14. public List<User> getUserList();
  15. @Insert ( "insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())" )
  16. public int add(User user);
  17. @Update ( "UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}" )
  18. public int update(@Param("id") Integer id, @Param("user") User user);
  19. @Delete ( "DELETE from tb_user where id = #{id} " )
  20. public int delete(Integer id);
  21. }

Mybatis 注解使用 http://www.mybatis.org/mybatis-3/zh/java-api.html

UserService.class

  1. package cn.saytime.service;
  2. import cn.saytime.bean.User;
  3. import org.springframework.stereotype.Service;
  4. import java.util.List;
  5. /**
  6. * @ClassName cn.saytime.service.UserService
  7. * @Description
  8. */
  9. public interface UserService {
  10. User getUserById(Integer id);
  11. public List<User> getUserList();
  12. public int add(User user);
  13. public int update(Integer id, User user);
  14. public int delete(Integer id);
  15. }

UserServiceimpl.class

  1. package cn .saytime .service .impl;
  2. import cn .saytime .bean .User;
  3. import cn .saytime .mapper .UserMapper;
  4. import cn .saytime .service .UserService;
  5. import org .springframework .beans .factory .annotation .Autowired;
  6. import org .springframework .stereotype .Service;
  7. import java .util .List;
  8. /**
  9. * @ClassName cn.saytime.service.impl.UserServiceImpl
  10. * @Description
  11. */
  12. @Service
  13. public class UserServiceImpl implements UserService {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Override
  17. public User getUserById(Integer id) {
  18. return userMapper .getUserById( id);
  19. }
  20. @Override
  21. public List<User> getUserList() {
  22. return userMapper .getUserList();
  23. }
  24. @Override
  25. public int add(User user) {
  26. return userMapper .add( user);
  27. }
  28. @Override
  29. public int update(Integer id, User user) {
  30. return userMapper .update( id, user);
  31. }
  32. @Override
  33. public int delete(Integer id) {
  34. return userMapper .delete( id);
  35. }
  36. }

JsonResult.class 通用json返回类

  1. package cn.saytime.bean;
  2. public class JsonResult {
  3. private String status = null;
  4. private Object result = null;
  5. public JsonResult status(String status) {
  6. this.status = status;
  7. return this;
  8. }
  9. // Getter Setter
  10. }

UserController.class(Restful风格

  1. package cn.saytime.web;
  2. import cn.saytime.bean.JsonResult;
  3. import cn.saytime.bean.User;
  4. import cn.saytime.service.UserService;
  5. import org.springframework.beans.factory. annotation.Autowired;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.web.bind. annotation.PathVariable;
  9. import org.springframework.web.bind. annotation.RequestBody;
  10. import org.springframework.web.bind. annotation.RequestMapping;
  11. import org.springframework.web.bind. annotation.RequestMethod;
  12. import org.springframework.web.bind. annotation.RequestParam;
  13. import org.springframework.web.bind. annotation.RestController;
  14. import java.util.List;
  15. /**
  16. * @ClassName cn.saytime.web.UserController
  17. * @Description
  18. * @date 2017-07-04 22:46:14
  19. */
  20. @RestController
  21. public class UserController {
  22. @Autowired
  23. private UserService userService;
  24. /**
  25. * 根据ID查询用户
  26. * @param id
  27. * @return
  28. */
  29. @RequestMapping (value = "user/{id}" , method = RequestMethod.GET)
  30. public ResponseEntity<JsonResult> getUserById ( @PathVariable (value = "id" ) Integer id){
  31. JsonResult r = new JsonResult();
  32. try {
  33. User user = userService.getUserById(id);
  34. r.setResult(user);
  35. r.setStatus( "ok");
  36. } catch (Exception e) {
  37. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  38. r.setStatus( "error");
  39. e.printStackTrace();
  40. }
  41. return ResponseEntity.ok(r);
  42. }
  43. /**
  44. * 查询用户列表
  45. * @return
  46. */
  47. @RequestMapping (value = "users" , method = RequestMethod.GET)
  48. public ResponseEntity<JsonResult> getUserList (){
  49. JsonResult r = new JsonResult();
  50. try {
  51. List<User> users = userService.getUserList();
  52. r.setResult(users);
  53. r.setStatus( "ok");
  54. } catch (Exception e) {
  55. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  56. r.setStatus( "error");
  57. e.printStackTrace();
  58. }
  59. return ResponseEntity.ok(r);
  60. }
  61. /**
  62. * 添加用户
  63. * @param user
  64. * @return
  65. */
  66. @RequestMapping (value = "user" , method = RequestMethod.POST)
  67. public ResponseEntity<JsonResult> add ( @RequestBody User user){
  68. JsonResult r = new JsonResult();
  69. try {
  70. int orderId = userService.add(user);
  71. if (orderId < 0) {
  72. r.setResult(orderId);
  73. r.setStatus( "fail");
  74. } else {
  75. r.setResult(orderId);
  76. r.setStatus( "ok");
  77. }
  78. } catch (Exception e) {
  79. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  80. r.setStatus( "error");
  81. e.printStackTrace();
  82. }
  83. return ResponseEntity.ok(r);
  84. }
  85. /**
  86. * 根据id删除用户
  87. * @param id
  88. * @return
  89. */
  90. @RequestMapping (value = "user/{id}" , method = RequestMethod.DELETE)
  91. public ResponseEntity<JsonResult> delete ( @PathVariable (value = "id" ) Integer id){
  92. JsonResult r = new JsonResult();
  93. try {
  94. int ret = userService.delete(id);
  95. if (ret < 0) {
  96. r.setResult(ret);
  97. r.setStatus( "fail");
  98. } else {
  99. r.setResult(ret);
  100. r.setStatus( "ok");
  101. }
  102. } catch (Exception e) {
  103. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  104. r.setStatus( "error");
  105. e.printStackTrace();
  106. }
  107. return ResponseEntity.ok(r);
  108. }
  109. /**
  110. * 根据id修改用户信息
  111. * @param user
  112. * @return
  113. */
  114. @RequestMapping (value = "user/{id}" , method = RequestMethod.PUT)
  115. public ResponseEntity<JsonResult> update ( @PathVariable ( "id" ) Integer id, @RequestBody User user){
  116. JsonResult r = new JsonResult();
  117. try {
  118. int ret = userService.update(id, user);
  119. if (ret < 0) {
  120. r.setResult(ret);
  121. r.setStatus( "fail");
  122. } else {
  123. r.setResult(ret);
  124. r.setStatus( "ok");
  125. }
  126. } catch (Exception e) {
  127. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  128. r.setStatus( "error");
  129. e.printStackTrace();
  130. }
  131. return ResponseEntity.ok(r);
  132. }
  133. }

Application.java

  1. package cn.saytime;
  2. import org.mybatis.spring. annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan ( "cn.saytime.mapper" )
  7. public class SpringbootMybaitsApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringbootMybaitsApplication. class, args);
  10. }
  11. }

使用PostMan通过测试。

2.配置文件版

加入配置文件

  1. mybatis:
  2. mapper- locations: classpath:mybatis /mapper/*.xml
  3. config- location: classpath:mybatis/mybatis-config.xml

项目目录结构:

这里写图片描述

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

UserMapper.class

  1. package cn .saytime .mapper;
  2. import cn .saytime .bean .User;
  3. import org .apache .ibatis .annotations .Delete;
  4. import org .apache .ibatis .annotations .Insert;
  5. import org .apache .ibatis .annotations .Param;
  6. import org .apache .ibatis .annotations .Select;
  7. import org .apache .ibatis .annotations .Update;
  8. import org .springframework .stereotype .Repository;
  9. import java .util .List;
  10. /**
  11. * @ClassName cn.saytime.mapper.UesrMapper
  12. * @Description
  13. */
  14. @Repository
  15. public interface UserMapper {
  16. User getUserById( Integer id);
  17. public List< User> getUserList();
  18. public int add( User user);
  19. public int update( @Param("id") Integer id, @Param("user") User user);
  20. public int delete( Integer id);
  21. }

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <typeAliases>
  7. </typeAliases>
  8. </configuration>

userMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="cn.saytime.mapper.UserMapper" >
  4. <resultMap id="BaseResultMap" type="cn.saytime.bean.User" >
  5. <id column="id" property="id" jdbcType="INTEGER" />
  6. <result column="username" property="username" jdbcType="VARCHAR" />
  7. <result column="age" property="age" jdbcType="INTEGER" />
  8. <result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
  9. </resultMap>
  10. <sql id="Base_Column_List" >
  11. id, username, age, ctm
  12. </sql>
  13. <select id="getUserList" resultMap="BaseResultMap" >
  14. SELECT
  15. <include refid="Base_Column_List" />
  16. FROM tb_user
  17. </select>
  18. <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
  19. SELECT
  20. <include refid="Base_Column_List" />
  21. FROM tb_user
  22. WHERE id = #{id}
  23. </select>
  24. <insert id="add" parameterType="cn.saytime.bean.User" >
  25. INSERT INTO
  26. tb_user
  27. (username,age,ctm)
  28. VALUES
  29. (#{username}, #{age}, now())
  30. </insert>
  31. <update id="update" parameterType="java.util.Map" >
  32. UPDATE
  33. tb_user
  34. SET
  35. username = #{user.username},age = #{user.age}
  36. WHERE
  37. id = #{id}
  38. </update>
  39. <delete id="delete" parameterType="java.lang.Integer" >
  40. DELETE FROM
  41. tb_user
  42. WHERE
  43. id = #{id}
  44. </delete>
  45. </mapper>

上面这种方式也使用PostMan通过测试。

五、简要说明

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

  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-web </artifactId>
  4. </dependency>

而这里是mybatis为spring提供的starter依赖,所以依赖地址是:

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot </groupId>
  3. <artifactId>mybatis-spring-boot-starter </artifactId>
  4. <version>1.3.0 </version>
  5. </dependency>

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

SpringBoot自己集成的starter依赖,可以查看 http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#using-boot-starter

版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/saytime https://blog.csdn.net/saytime/article/details/74783296

怎么说了,写博客虽然是一件很费时间的事情,而且还是个菜鸟,但是如果写的东西能够帮助到别人,还是值得开心的。

回顾:

上篇写了JdbcTemplate,但是想到使用Mybatis,JPA的人估计不少,所以这篇写一下SpringBoot整合Mybatis,JPA的话以后有时间再弄,因为自己也没用过。

一、数据准备

其实还是上篇的,以防有人是直接看这篇的,就还是贴出来吧。

  1. CREATE TABLE `tb_user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  3. `username` varchar(50) NOT NULL COMMENT '用户名',
  4. `age` int(11) NOT NULL COMMENT '年龄',
  5. `ctm` datetime NOT NULL COMMENT '创建时间',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8
  1. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ;
  2. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
  3. INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;

二、引入依赖

  1. <!-- Spring-Mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot </groupId>
  4. <artifactId>mybatis-spring-boot-starter </artifactId>
  5. <version>1.3.0 </version>
  6. </dependency>
  7. <!-- MySQL -->
  8. <dependency>
  9. <groupId>mysql </groupId>
  10. <artifactId>mysql-connector-java </artifactId>
  11. </dependency>

另外web依赖也需要,因为我们采用MVC模式。

  1. <!-- Add typical dependencies for a web application -->
  2. <dependency>
  3. <groupId>org.springframework.boot </groupId>
  4. <artifactId>spring-boot-starter-web </artifactId>
  5. </dependency>

三、数据库配置文件

  1. spring:
  2. datasource:
  3. driver-class-name : com.mysql.jdbc.Driver
  4. url: jdbc: mysql: //localhost:3306/db_user
  5. username: root
  6. password: root

四、代码

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

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

1.无配置文件注解版

加入配置文件

  1. mybatis:
  2. type-aliases-package: cn .saytime .bean

这里写图片描述

实体类User.class

  1. package cn.saytime.bean;
  2. import java.util.Date;
  3. /**
  4. * @ClassName cn.saytime.bean.User
  5. * @Description
  6. * @date 2017-07-04 22:47:28
  7. */
  8. public class User {
  9. private int id;
  10. private String username;
  11. private int age;
  12. private Date ctm;
  13. public User() {
  14. }
  15. public User(String username, int age) {
  16. this.username = username;
  17. this.age = age;
  18. this.ctm = new Date();
  19. }
  20. // Getter、Setter
  21. }

UserMapper.class

  1. package cn.saytime.mapper;
  2. import cn.saytime.bean.User;
  3. import org.apache.ibatis.annotations.Delete;
  4. import org.apache.ibatis.annotations.Insert;
  5. import org.apache.ibatis.annotations.Param;
  6. import org.apache.ibatis.annotations.Select;
  7. import org.apache.ibatis.annotations.Update;
  8. import java.util.List;
  9. // @Mapper 这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
  10. public interface UserMapper {
  11. @Select ( "SELECT * FROM tb_user WHERE id = #{id}" )
  12. User getUserById(Integer id);
  13. @Select ( "SELECT * FROM tb_user" )
  14. public List<User> getUserList();
  15. @Insert ( "insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())" )
  16. public int add(User user);
  17. @Update ( "UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}" )
  18. public int update(@Param("id") Integer id, @Param("user") User user);
  19. @Delete ( "DELETE from tb_user where id = #{id} " )
  20. public int delete(Integer id);
  21. }

Mybatis 注解使用 http://www.mybatis.org/mybatis-3/zh/java-api.html

UserService.class

  1. package cn.saytime.service;
  2. import cn.saytime.bean.User;
  3. import org.springframework.stereotype.Service;
  4. import java.util.List;
  5. /**
  6. * @ClassName cn.saytime.service.UserService
  7. * @Description
  8. */
  9. public interface UserService {
  10. User getUserById(Integer id);
  11. public List<User> getUserList();
  12. public int add(User user);
  13. public int update(Integer id, User user);
  14. public int delete(Integer id);
  15. }

UserServiceimpl.class

  1. package cn .saytime .service .impl;
  2. import cn .saytime .bean .User;
  3. import cn .saytime .mapper .UserMapper;
  4. import cn .saytime .service .UserService;
  5. import org .springframework .beans .factory .annotation .Autowired;
  6. import org .springframework .stereotype .Service;
  7. import java .util .List;
  8. /**
  9. * @ClassName cn.saytime.service.impl.UserServiceImpl
  10. * @Description
  11. */
  12. @Service
  13. public class UserServiceImpl implements UserService {
  14. @Autowired
  15. private UserMapper userMapper;
  16. @Override
  17. public User getUserById(Integer id) {
  18. return userMapper .getUserById( id);
  19. }
  20. @Override
  21. public List<User> getUserList() {
  22. return userMapper .getUserList();
  23. }
  24. @Override
  25. public int add(User user) {
  26. return userMapper .add( user);
  27. }
  28. @Override
  29. public int update(Integer id, User user) {
  30. return userMapper .update( id, user);
  31. }
  32. @Override
  33. public int delete(Integer id) {
  34. return userMapper .delete( id);
  35. }
  36. }

JsonResult.class 通用json返回类

  1. package cn.saytime.bean;
  2. public class JsonResult {
  3. private String status = null;
  4. private Object result = null;
  5. public JsonResult status(String status) {
  6. this.status = status;
  7. return this;
  8. }
  9. // Getter Setter
  10. }

UserController.class(Restful风格

  1. package cn.saytime.web;
  2. import cn.saytime.bean.JsonResult;
  3. import cn.saytime.bean.User;
  4. import cn.saytime.service.UserService;
  5. import org.springframework.beans.factory. annotation.Autowired;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.web.bind. annotation.PathVariable;
  9. import org.springframework.web.bind. annotation.RequestBody;
  10. import org.springframework.web.bind. annotation.RequestMapping;
  11. import org.springframework.web.bind. annotation.RequestMethod;
  12. import org.springframework.web.bind. annotation.RequestParam;
  13. import org.springframework.web.bind. annotation.RestController;
  14. import java.util.List;
  15. /**
  16. * @ClassName cn.saytime.web.UserController
  17. * @Description
  18. * @date 2017-07-04 22:46:14
  19. */
  20. @RestController
  21. public class UserController {
  22. @Autowired
  23. private UserService userService;
  24. /**
  25. * 根据ID查询用户
  26. * @param id
  27. * @return
  28. */
  29. @RequestMapping (value = "user/{id}" , method = RequestMethod.GET)
  30. public ResponseEntity<JsonResult> getUserById ( @PathVariable (value = "id" ) Integer id){
  31. JsonResult r = new JsonResult();
  32. try {
  33. User user = userService.getUserById(id);
  34. r.setResult(user);
  35. r.setStatus( "ok");
  36. } catch (Exception e) {
  37. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  38. r.setStatus( "error");
  39. e.printStackTrace();
  40. }
  41. return ResponseEntity.ok(r);
  42. }
  43. /**
  44. * 查询用户列表
  45. * @return
  46. */
  47. @RequestMapping (value = "users" , method = RequestMethod.GET)
  48. public ResponseEntity<JsonResult> getUserList (){
  49. JsonResult r = new JsonResult();
  50. try {
  51. List<User> users = userService.getUserList();
  52. r.setResult(users);
  53. r.setStatus( "ok");
  54. } catch (Exception e) {
  55. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  56. r.setStatus( "error");
  57. e.printStackTrace();
  58. }
  59. return ResponseEntity.ok(r);
  60. }
  61. /**
  62. * 添加用户
  63. * @param user
  64. * @return
  65. */
  66. @RequestMapping (value = "user" , method = RequestMethod.POST)
  67. public ResponseEntity<JsonResult> add ( @RequestBody User user){
  68. JsonResult r = new JsonResult();
  69. try {
  70. int orderId = userService.add(user);
  71. if (orderId < 0) {
  72. r.setResult(orderId);
  73. r.setStatus( "fail");
  74. } else {
  75. r.setResult(orderId);
  76. r.setStatus( "ok");
  77. }
  78. } catch (Exception e) {
  79. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  80. r.setStatus( "error");
  81. e.printStackTrace();
  82. }
  83. return ResponseEntity.ok(r);
  84. }
  85. /**
  86. * 根据id删除用户
  87. * @param id
  88. * @return
  89. */
  90. @RequestMapping (value = "user/{id}" , method = RequestMethod.DELETE)
  91. public ResponseEntity<JsonResult> delete ( @PathVariable (value = "id" ) Integer id){
  92. JsonResult r = new JsonResult();
  93. try {
  94. int ret = userService.delete(id);
  95. if (ret < 0) {
  96. r.setResult(ret);
  97. r.setStatus( "fail");
  98. } else {
  99. r.setResult(ret);
  100. r.setStatus( "ok");
  101. }
  102. } catch (Exception e) {
  103. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  104. r.setStatus( "error");
  105. e.printStackTrace();
  106. }
  107. return ResponseEntity.ok(r);
  108. }
  109. /**
  110. * 根据id修改用户信息
  111. * @param user
  112. * @return
  113. */
  114. @RequestMapping (value = "user/{id}" , method = RequestMethod.PUT)
  115. public ResponseEntity<JsonResult> update ( @PathVariable ( "id" ) Integer id, @RequestBody User user){
  116. JsonResult r = new JsonResult();
  117. try {
  118. int ret = userService.update(id, user);
  119. if (ret < 0) {
  120. r.setResult(ret);
  121. r.setStatus( "fail");
  122. } else {
  123. r.setResult(ret);
  124. r.setStatus( "ok");
  125. }
  126. } catch (Exception e) {
  127. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  128. r.setStatus( "error");
  129. e.printStackTrace();
  130. }
  131. return ResponseEntity.ok(r);
  132. }
  133. }

Application.java

  1. package cn.saytime;
  2. import org.mybatis.spring. annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan ( "cn.saytime.mapper" )
  7. public class SpringbootMybaitsApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringbootMybaitsApplication. class, args);
  10. }
  11. }

使用PostMan通过测试。

2.配置文件版

加入配置文件

  1. mybatis:
  2. mapper- locations: classpath:mybatis /mapper/*.xml
  3. config- location: classpath:mybatis/mybatis-config.xml

项目目录结构:

这里写图片描述

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

UserMapper.class

  1. package cn .saytime .mapper;
  2. import cn .saytime .bean .User;
  3. import org .apache .ibatis .annotations .Delete;
  4. import org .apache .ibatis .annotations .Insert;
  5. import org .apache .ibatis .annotations .Param;
  6. import org .apache .ibatis .annotations .Select;
  7. import org .apache .ibatis .annotations .Update;
  8. import org .springframework .stereotype .Repository;
  9. import java .util .List;
  10. /**
  11. * @ClassName cn.saytime.mapper.UesrMapper
  12. * @Description
  13. */
  14. @Repository
  15. public interface UserMapper {
  16. User getUserById( Integer id);
  17. public List< User> getUserList();
  18. public int add( User user);
  19. public int update( @Param("id") Integer id, @Param("user") User user);
  20. public int delete( Integer id);
  21. }

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <typeAliases>
  7. </typeAliases>
  8. </configuration>

userMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="cn.saytime.mapper.UserMapper" >
  4. <resultMap id="BaseResultMap" type="cn.saytime.bean.User" >
  5. <id column="id" property="id" jdbcType="INTEGER" />
  6. <result column="username" property="username" jdbcType="VARCHAR" />
  7. <result column="age" property="age" jdbcType="INTEGER" />
  8. <result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
  9. </resultMap>
  10. <sql id="Base_Column_List" >
  11. id, username, age, ctm
  12. </sql>
  13. <select id="getUserList" resultMap="BaseResultMap" >
  14. SELECT
  15. <include refid="Base_Column_List" />
  16. FROM tb_user
  17. </select>
  18. <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
  19. SELECT
  20. <include refid="Base_Column_List" />
  21. FROM tb_user
  22. WHERE id = #{id}
  23. </select>
  24. <insert id="add" parameterType="cn.saytime.bean.User" >
  25. INSERT INTO
  26. tb_user
  27. (username,age,ctm)
  28. VALUES
  29. (#{username}, #{age}, now())
  30. </insert>
  31. <update id="update" parameterType="java.util.Map" >
  32. UPDATE
  33. tb_user
  34. SET
  35. username = #{user.username},age = #{user.age}
  36. WHERE
  37. id = #{id}
  38. </update>
  39. <delete id="delete" parameterType="java.lang.Integer" >
  40. DELETE FROM
  41. tb_user
  42. WHERE
  43. id = #{id}
  44. </delete>
  45. </mapper>

上面这种方式也使用PostMan通过测试。

五、简要说明

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

  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-web </artifactId>
  4. </dependency>

而这里是mybatis为spring提供的starter依赖,所以依赖地址是:

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot </groupId>
  3. <artifactId>mybatis-spring-boot-starter </artifactId>
  4. <version>1.3.0 </version>
  5. </dependency>

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

SpringBoot自己集成的starter依赖,可以查看 http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#using-boot-starter

版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/saytime https://blog.csdn.net/saytime/article/details/74783296

猜你喜欢

转载自blog.csdn.net/eeeeasy/article/details/80831587