经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot(五) SpringBoot整合mybatis
来源:cnblogs  作者:丹丹蛋蛋  时间:2019/9/25 9:33:00  对本文有异议

一:项目结构:

 

 

 

 

 

:pom文件如下:

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.4.RELEASE</version>
  5. </parent>
  6.  
  7. <dependencies>
  8. <!-- Spring-Mybatis -->
  9. <dependency>
  10. <groupId>org.mybatis.spring.boot</groupId>
  11. <artifactId>mybatis-spring-boot-starter</artifactId>
  12. <version>1.3.0</version>
  13. </dependency>
  14. <!-- jdbcTemplate -->
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-jdbc</artifactId>
  18. </dependency>
  19. <!-- MySQL连接 -->
  20. <dependency>
  21. <groupId>mysql</groupId>
  22. <artifactId>mysql-connector-java</artifactId>
  23. <scope>runtime</scope>
  24. </dependency>
  25. <!-- Add typical dependencies for a web application -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. </dependencies>

三:数据库配置:

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

四:代码说明:

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

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

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

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

 

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

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


    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

 

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

测试:

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

2.配置文件版

加入配置文件

 

 代码部分,相比于上面那种方式,改变的只有配置文件以及下面几个部分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. }


    UserServiceImpl类:

 

  1.  

import java.util.List;

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

import org.springframework.stereotype.Service;

  1.  

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

  1.  


@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserDao userDao;

@Autowired
private UserMapper1 userMapper;

  1.  

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

  1.  

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

}

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

原文链接:http://www.cnblogs.com/2019lgg/p/11580718.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号