spring boot 整合 mybatis

亦凉 2022-05-14 18:51 331阅读 0赞

1、在pom.xml中添加mysql和mybatis 的maven依赖

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.3.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <scope>runtime</scope>
  10. </dependency>

2、在src/main/resources 目录下创建mybatis目录,并在下面创建mybatis-config.xml,同时创建一个mapper目录,用于存放sql映射文件

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xEWTEwMTY_size_27_color_FFFFFF_t_70

mybatis-config.xml 内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <typeAliases>
  5. <typeAlias alias="Integer" type="java.lang.Integer" />
  6. <typeAlias alias="Long" type="java.lang.Long" />
  7. <typeAlias alias="HashMap" type="java.util.HashMap" />
  8. <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
  9. <typeAlias alias="ArrayList" type="java.util.ArrayList" />
  10. <typeAlias alias="LinkedList" type="java.util.LinkedList" />
  11. </typeAliases>
  12. </configuration>

3、在application.properties中添加数据库连接信息 和 mybatis配置信息

  1. #mysql
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/boot_v2?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
  4. spring.datasource.username=root
  5. spring.datasource.password=root
  6. #mybatis
  7. #扫描指定路径下的实体,并用实体的简单名称作为别名
  8. mybatis.type-aliases-package=com.ldy.bootv2.demo.entity
  9. #自动扫描加载mybatis配置文件
  10. mybatis.config-location=classpath:mybatis/mybatis-config.xml
  11. #自动扫描加载Sql映射文件
  12. mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
  13. #mapper目录下分多个模块时可以这样写
  14. #mybatis.mapper-locations=classpath:mybatis/mapper/*/*.xml

4、创建数据库表

  1. CREATE TABLE `user` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `age` int(11) DEFAULT NULL,
  4. `name` varchar(255) DEFAULT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
  7. INSERT INTO `user` VALUES ('1', '20', 'zs'), ('2', '21', 'ls');

5、编写数据库表对应实体类 :UserEntity.java

  1. package com.ldy.bootv2.demo.entity;
  2. import java.io.Serializable;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. @ApiModel
  6. public class UserEntity implements Serializable {
  7. private static final long serialVersionUID = 1L;
  8. @ApiModelProperty(value="id,新建时不传,修改时传")
  9. private Integer id;
  10. @ApiModelProperty(value="名称")
  11. private String userName;
  12. @ApiModelProperty(value="年龄")
  13. private Integer userAge;
  14. public Integer getId() {
  15. return id;
  16. }
  17. public void setId(Integer id) {
  18. this.id = id;
  19. }
  20. public String getUserName() {
  21. return userName;
  22. }
  23. public void setUserName(String userName) {
  24. this.userName = userName;
  25. }
  26. public Integer getUserAge() {
  27. return userAge;
  28. }
  29. public void setUserAge(Integer userAge) {
  30. this.userAge = userAge;
  31. }
  32. }

6、编写Dao层代码:UserMapper.java

  1. package com.ldy.bootv2.demo.mapper;
  2. import java.util.List;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import com.ldy.bootv2.demo.entity.UserEntity;
  5. @Mapper
  6. public interface UserMapper {
  7. List<UserEntity> getAll();
  8. UserEntity getOne(Integer id);
  9. int insert(UserEntity user);
  10. int update(UserEntity user);
  11. int delete(Integer id);
  12. }

7、编写Controller:UserController

  1. package com.ldy.bootv2.demo.controller;
  2. import java.util.List;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.DeleteMapping;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.ModelAttribute;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.PutMapping;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import com.ldy.bootv2.demo.entity.UserEntity;
  14. import com.ldy.bootv2.demo.mapper.UserMapper;
  15. import io.swagger.annotations.Api;
  16. import io.swagger.annotations.ApiOperation;
  17. import io.swagger.annotations.ApiParam;
  18. @Api(tags = "用户信息管理接口-API")
  19. @RestController
  20. @RequestMapping("/user")
  21. public class UserController {
  22. private static Logger logger = LoggerFactory.getLogger(UserController.class);
  23. @Autowired
  24. UserMapper userMapper;
  25. @GetMapping("/findAll")
  26. @ApiOperation("查询全部用户")
  27. public List<UserEntity> findAll() {
  28. logger.info("您调用了findAll接口");
  29. return userMapper.getAll();
  30. }
  31. @GetMapping("/getOne/{id}")
  32. @ApiOperation("根据ID查询用户")
  33. public UserEntity getOne(@ApiParam(value="用户id",required=true) @PathVariable("id") Integer id) {
  34. logger.info("您调用了getOne接口");
  35. return userMapper.getOne(id);
  36. }
  37. @PutMapping("/saveOrUpdate")
  38. @ApiOperation("新增或者修改用户")
  39. public String saveOrUpdate(@ModelAttribute UserEntity entity) {
  40. logger.info("您调用了saveOrUpdate接口");
  41. try {
  42. if(null == entity.getId()) {
  43. userMapper.insert(entity);
  44. }else {
  45. userMapper.update(entity);
  46. }
  47. } catch (Exception e) {
  48. logger.error("失败,原因:" + e.getMessage());
  49. return "error";
  50. }
  51. return "success";
  52. }
  53. @DeleteMapping("/delete/{id}")
  54. @ApiOperation("根据ID删除用户")
  55. public String deleteById(@ApiParam(value="用户id",required=true) @PathVariable("id") Integer id) {
  56. logger.info("您调用了delete接口");
  57. try {
  58. userMapper.delete(id);
  59. } catch (Exception e) {
  60. logger.error("失败,原因:" + e.getMessage());
  61. return "error";
  62. }
  63. return "success";
  64. }
  65. }

8、运行项目,打开swagger页面,测试接口正常,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xEWTEwMTY_size_27_color_FFFFFF_t_70 1

源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xEWTEwMTY_size_27_color_FFFFFF_t_70 2

发表评论

表情:
评论列表 (有 0 条评论,331人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring boot整合Mybatis

    时隔两个月的再来写博客的感觉怎么样呢,只能用“棒”来形容了。闲话少说,直接入正题,之前的博客中有说过,将spring与mybatis整个后开发会更爽,基于现在springboo

    相关 Spring boot整合Mybatis

    ​ 抽空写个小demo,顺便温习下知识,自从用了Spring boot之后,怎一个爽字了得,开发起来太舒服了,目前Springboot已经成为了开发界的主流框架了,在此就将Sp