美文网首页
springboot 之集成mybatis

springboot 之集成mybatis

作者: xuefly3 | 来源:发表于2019-12-20 15:29 被阅读0次

    前言

    一直没机会做spring生态圈的框架,公司选择的是一些小众的微服务,鉴于此考虑,丰富自己的技术栈,花了两天时间从网上各网站上学习了springboot一些基础知识。
    本章只介绍springboot微服务集成mybatis,而且是不使用xml形式的用法。

    环境准备

    • IntelliJ IDEA
    • MySQL(提前建库,建表用于数据访问)
    • 前一章中搭建的微服务框架

    开始集成

    1. pom.xml中增加依赖包


      依赖包.png
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.3</version>
            </dependency>
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>
    
    1. 配置application.yml,增加datasource和mytabis配置


      yml配置.png

      (driver-class-name配置成com.mysql.jdbc.Driver,服务运行时提示此driver已过期,使用最新的配置:com.mysql.cj.jdbc.Driver)

    spring:
      #日志记录模式
      profiles:
        active: dev
      banner:
        charset: "UTF-8"
        location: classpath:/banner.txt
      datasource:
        url: jdbc:mysql://localhost:3306/test
        username: root
        password: xxx
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    mybatis:
      configuration:
        cache-enabled: false
        map-underscore-to-camel-case: true
        use-generated-keys: true
        default-executor-type: reuse
        default-statement-timeout: 600
    
    1. DemoApplication中增加MapperScan


      mapperScan.png
    package com.example.demo;
    
    import lombok.extern.slf4j.Slf4j;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @SpringBootApplication
    @EnableSwagger2
    @MapperScan("com.example.demo.mapper")
    @EnableScheduling
    @EnableTransactionManagement
    @Slf4j
    public class DemoApplication {
    
        public static void main(String[] args) {
            log.info("DemoApplication run enter...");
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    
    1. 在demo包下并列新建三个包:entity(实体类),mapper(数据操作映射类),service(业务操作类)


      新建包.png
    2. entity下新建实体类User


      实体类.png

      (通过lombok的注解简化了实体类的代码,只需要定义fields即可,再通过@Data,@Getter,@Setter注解引入get/set方法)

    package com.example.demo.entity;
    import lombok.Data;
    import lombok.Getter;
    import lombok.Setter;
    
    import java.util.Date;
    
    /**
     * 类功能描述:<br>
     * <ul>
     * <li>类功能描述1<br>
     * <li>类功能描述2<br>
     * <li>类功能描述3<br>
     * </ul>
     * 修改记录:<br>
     * <ul>
     * <li>修改记录描述1<br>
     * <li>修改记录描述2<br>
     * <li>修改记录描述3<br>
     * </ul>
     *
     * @author xuefl
     * @version 5.0 since 2019-12-18
     */
    @Data
    @Getter
    @Setter
    public class User {
        private String id;
        private String userName;
        private String userPasswd;
        private Integer userType;
        private String userPhone;
        private String userMailbox;
        private Integer userSafeState;
        private String userSafeAddress;
        private Integer userLoginCount;
        private Date userLoginTime;
        private Integer userExpiryDateCount;
        private Date userExpiryDate;
        private Integer userPassExpiryDateCount;
        private Date userPassExpiryDate;
        private Integer userSessionTime;
        private Date userCreateTime;
        private String userDetails;
    }
    
    1. mapper下新建UserMapper接口


      UserMapper.png
    package com.example.demo.mapper;
    /**
     * 类功能描述:<br>
     * <ul>
     * <li>类功能描述1<br>
     * <li>类功能描述2<br>
     * <li>类功能描述3<br>
     * </ul>
     * 修改记录:<br>
     * <ul>
     * <li>修改记录描述1<br>
     * <li>修改记录描述2<br>
     * <li>修改记录描述3<br>
     * </ul>
     *
     * @author xuefl
     * @version 5.0 since 2019-12-18
     */
    
    import com.example.demo.entity.User;
    import org.apache.ibatis.annotations.*;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    @Component(value = "userMapper")
    public interface UserMapper {
        @Results({
                @Result(property = "id", column = "id"),
                @Result(property = "userName", column = "userName"),
                @Result(property = "userPasswd", column = "userPasswd"),
                @Result(property = "userType", column = "userType"),
                @Result(property = "userPhone", column = "userPhone"),
                @Result(property = "userMailbox", column = "userMailbox"),
                @Result(property = "userDetails", column = "userDetails")
        })
        @Select("SELECT * FROM user ")
        List<User> selectAll();
        @Results({
                @Result(property = "id", column = "id"),
                @Result(property = "userName", column = "userName"),
                @Result(property = "userPasswd", column = "userPasswd"),
                @Result(property = "userType", column = "userType"),
                @Result(property = "userPhone", column = "userPhone"),
                @Result(property = "userMailbox", column = "userMailbox"),
                @Result(property = "userDetails", column = "userDetails")
        })
        @Select("SELECT * FROM user WHERE id = #{id} ")
        User getOne(String id);
    
        @Delete("DELETE FROM user WHERE id =#{id} ")
        void delete(String id);
    
        @Insert("INSERT INTO user(id,userName,userPasswd,userType,userPhone,userMailbox,userDetails)" +
                " VALUES(#{id}, #{userName}, #{userPasswd}, #{userType},#{userPhone},#{userMailbox},#{userDetails}) ")
        void insert(User user);
    
        @Update("UPDATE user SET userName=#{userName},userPasswd=#{userPasswd} WHERE id =#{id}")
        void update(User user);
    }
    
    1. service下新建UserService接口


      userService.png
    package com.example.demo.service;
    import com.example.demo.entity.User;
    
    import java.util.List;
    
    /**
     * 类功能描述:<br>
     * <ul>
     * <li>类功能描述1<br>
     * <li>类功能描述2<br>
     * <li>类功能描述3<br>
     * </ul>
     * 修改记录:<br>
     * <ul>
     * <li>修改记录描述1<br>
     * <li>修改记录描述2<br>
     * <li>修改记录描述3<br>
     * </ul>
     *
     * @author xuefl
     * @version 5.0 since 2019-12-18
     */
    public interface UserService {
        List<User> selectAll();
    
        User getOne(String id);
    
        void delete(String id);
    
        void insert(User user);
    
        void update(User user);
    }
    
    1. service包下新建impl包用于存放接口实现类,并在impl下新建UserServiceImpl实现类


      UserServiceImpl实现类.png
    package com.example.demo.service.impl;
    import com.example.demo.entity.User;
    import com.example.demo.mapper.UserMapper;
    import com.example.demo.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * 类功能描述:<br>
     * <ul>
     * <li>类功能描述1<br>
     * <li>类功能描述2<br>
     * <li>类功能描述3<br>
     * </ul>
     * 修改记录:<br>
     * <ul>
     * <li>修改记录描述1<br>
     * <li>修改记录描述2<br>
     * <li>修改记录描述3<br>
     * </ul>
     *
     * @author xuefl
     * @version 5.0 since 2019-12-18
     */
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public List<User> selectAll() {
            return userMapper.selectAll();
        }
    
        @Override
        public User getOne(String id) {
            return userMapper.getOne(id);
        }
    
        @Override
        public void delete(String id) {
            userMapper.delete(id);
        }
    
        @Override
        public void insert(User user) {
            userMapper.insert(user);
        }
    
        @Override
        public void update(User user) {
            userMapper.update(user);
        }
    
    }
    

    实现类中注入userMapper,通过userMapper对user表做数据操作

    1. controller下新建UserController类,定义user对象的CRUD接口


      UserController.png
    package com.example.demo.controller;
    import com.example.demo.entity.User;
    import com.example.demo.service.UserService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
     * 类功能描述:<br>
     * <ul>
     * <li>类功能描述1<br>
     * <li>类功能描述2<br>
     * <li>类功能描述3<br>
     * </ul>
     * 修改记录:<br>
     * <ul>
     * <li>修改记录描述1<br>
     * <li>修改记录描述2<br>
     * <li>修改记录描述3<br>
     * </ul>
     *
     * @author xuefl
     * @version 5.0 since 2019-12-18
     */
    @RestController
    @Api(value = "SwaggerValue", tags={"SwaggerController"},description = "swagger应用",  produces = MediaType.APPLICATION_JSON_VALUE)
    public class UserController {
        @Resource
        private UserService userService;
        /**
         * 查询所有
         *
         * @return
         */
        @RequestMapping(value = "/users", method = RequestMethod.GET)
        @ApiOperation(value="users",httpMethod = "GET",notes="users",produces = MediaType.APPLICATION_JSON_VALUE)
        public List<User> selectAll() {
            return userService.selectAll();
        }
    
        /**
         * 根据id查询
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
        @ApiOperation(value="user",httpMethod = "GET",notes="user",produces = MediaType.APPLICATION_JSON_VALUE)
        public User getOne(@PathVariable("id") String id) {
            return userService.getOne(id);
        }
    
        /**
         * 根据id删除
         *
         * @param id
         */
        @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
        @ApiOperation(value="delete user",httpMethod = "DELETE",notes="delete user",produces = MediaType.APPLICATION_JSON_VALUE)
        public void deleteCourse(@ApiParam(name="id",value="id",required=true) @PathVariable("id") String id) {
            userService.delete(id);
        }
    
        /**
         * 新增
         *
         * @param user
         */
        @RequestMapping(value = "/user", method = RequestMethod.POST)
        @ApiOperation(value="insert user",httpMethod = "POST",notes="insert user",produces = MediaType.APPLICATION_JSON_VALUE)
        public void addUser(@ApiParam(name="user",value="user",required=true) @RequestBody User user) {
            userService.insert(user);
        }
    
        /**
         * 更新
         *
         * @param user
         */
        @RequestMapping(value = "/user", method = RequestMethod.PUT)
        @ApiOperation(value="update user",httpMethod = "PUT",notes="update user",produces = MediaType.APPLICATION_JSON_VALUE)
        public void updateUser(@ApiParam(name="user",value="user",required=true) @RequestBody User user) {
            userService.update(user);
        }
    
    }
    

    UserController中注入userService对象,直接在定义的接口实现类中实现业务的逻辑,(本文中涉及的@Api开头的注解是Swagger2组件的,后文中会做专题配置详解)

    1. 运行DemoApplication,直接访问接口:http://localhost:8081/api/users,可以看到接口返回消息
      接口测试.png
      其他接口测试结果就不展示了,以GET接口为例

    相关文章

      网友评论

          本文标题:springboot 之集成mybatis

          本文链接:https://www.haomeiwen.com/subject/vccinctx.html