zoukankan      html  css  js  c++  java
  • Spring Boot Sample 019之spring-boot-data-mybatis

    一、环境

    • Idea 2020.1
    • JDK 1.8
    • maven

    二、目的

    spring boot整合mybatis。

    三、步骤

    3.1、点击File -> New Project -> Spring Initializer,点击next

    3.2、在对应地方修改自己的项目信息

    3.3、选择Web依赖,选中Spring Web、Spring Data JDBC、MyBatis Framework、MySQL Driver。可以选择Spring Boot版本,本次默认为2.2.7,点击Next

    3.4、项目结构

    四、添加文件

    pom.xml文件
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>org.ouyushan</groupId>
        <artifactId>spring-boot-data-mybatis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-boot-data-mybatis</name>
        <description>MyBatis project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    application.properties文件
    ######   mysql     #######
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=root
    
    mybatis.configuration.mapUnderscoreToCamelCase=true
    UserInfo.java
    package org.ouyushan.springboot.data.mybatis.entity;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 14:10
     */
    public class UserInfo {
    
        private Long id;
    
        private String userName;
    
        private String password;
    
        private int age;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    UserInfoDao.java
    package org.ouyushan.springboot.data.mybatis.dao;
    
    import org.apache.ibatis.annotations.*;
    import org.ouyushan.springboot.data.mybatis.entity.UserInfo;
    
    import java.util.List;
    
    /**
     * @Description:
     * 与mybatis整合须在mapper接口添加注解,
     * 或者使用@MapperScan在启动类指定扫描路径
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 14:10
     */
    public interface UserInfoDao {
    
        /* 不需要返回主键 */
        @Insert("insert into user_info(user_name,password,age) values (#{userName},#{password},#{age})")
        int add(UserInfo userInfo);
    
        /* 需要返回主键 - 自增数据库*/
        @Insert("insert into user_info(user_name,password,age) values (#{userName},#{password},#{age})")
        @Options(useGeneratedKeys = true, keyProperty = "id")
        int addReturnKeyIncrement(UserInfo userInfo);
    
        /* 需要返回主键 - 非自增数据库*/
    /*    @Insert("insert into user_info(user_name,password,age) values (#{user_name},#{password},#{age})")
        @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", resultType = Long.class, before = false)
        int addReturnKeyNoIncrement(UserInfo userInfo);*/
    
        @Update("update user_info set user_name = #{userName},password = #{password}, age = #{age} where id = #{id}")
        int update(UserInfo userInfo);
    
        @Delete("delete from user_info where id = #{id}")
        int delete(Long id);
    
        @Select("select id,user_name userName,password,age from user_info where id = #{id}")
        UserInfo findUserInfo(Long id);
    
        @Select("select * from user_info")
        List<UserInfo> findUserInfoList();
    
    }
    UserInfoService.java
    package org.ouyushan.springboot.data.mybatis.service;
    
    import org.ouyushan.springboot.data.mybatis.entity.UserInfo;
    
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 14:15
     */
    public interface UserInfoService {
    
        int add(UserInfo userInfo);
    
        int update(UserInfo userInfo);
    
        int delete(Long id);
    
        UserInfo findUserInfo(Long id);
    
        List<UserInfo> findUserInfoList();
    }
    UserInfoServiceImpl.java
    package org.ouyushan.springboot.data.mybatis.service;
    
    import org.ouyushan.springboot.data.mybatis.dao.UserInfoDao;
    import org.ouyushan.springboot.data.mybatis.entity.UserInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 14:16
     */
    @Service("userInfoService")
    public class UserInfoServiceImpl implements UserInfoService {
    
        @Autowired
        private UserInfoDao userInfoDao;
    
        @Override
        public int add(UserInfo userInfo) {
            return this.userInfoDao.add(userInfo);
        }
    
        @Override
        public int update(UserInfo userInfo) {
            return this.userInfoDao.update(userInfo);
        }
    
        @Override
        public int delete(Long id) {
            return this.userInfoDao.delete(id);
        }
    
        @Override
        public UserInfo findUserInfo(Long id) {
            return this.userInfoDao.findUserInfo(id);
        }
    
        @Override
        public List<UserInfo> findUserInfoList() {
            return this.userInfoDao.findUserInfoList();
        }
    }
    UserInfoController.java
    package org.ouyushan.springboot.data.jparepository.controller;
    
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    import org.ouyushan.springboot.data.jparepository.service.UserInfoService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 11:03
     */
    @RestController
    @RequestMapping("/api/user")
    public class UserInfoController {
    
        @Autowired
        private UserInfoService userInfoService;
    
        /**
         * 查询个人信息
         *
         * @param id
         * @return
         */
        @GetMapping(value = "/getUser/{id}")
        public UserInfo getUserInfo(@PathVariable("id") Long id) {
            UserInfo userInfo = userInfoService.findUserInfo(id);
            if (userInfo == null) {
                throw new RuntimeException("查询为空");
            }
            return userInfo;
        }
    
        /**
         * 查询用户列表
         *
         * @return
         */
        @GetMapping(value = "/getUsers")
        public List<UserInfo> getUserInfoList() {
            List<UserInfo> userInfoList = this.userInfoService.findUserInfoList();
            if (userInfoList == null || userInfoList.size() == 0) {
                throw new RuntimeException("用户列表为空");
            }
            return userInfoList;
        }
    
        /**
         * 新增用户
         */
        @PostMapping(value = "/addUser")
        public void addUser(@RequestBody UserInfo userInfo) {
            try {
                this.userInfoService.add(userInfo);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("新增用户失败");
            }
        }
    
        /**
         * 更新用户
         *
         * @param
         */
        @PutMapping(value = "/updateUser")
        public void update(@RequestBody UserInfo userInfo) {
            try {
                this.userInfoService.update(userInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @DeleteMapping(value = "/delete/{id}")
        public void delete(@PathVariable("id") Long id) {
            try {
                this.userInfoService.delete(id);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("删除用户:" + id + " 失败");
            }
        }
    
    }
    SpringBootDataMybatisApplication.java
    package org.ouyushan.springboot.data.mybatis;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("org.ouyushan.springboot.data.mybatis.dao")
    public class SpringBootDataMybatisApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootDataMybatisApplication.class, args);
        }
    }

    五、测试

    分别运行以下测试用例
     
    SpringBootDataMybatisApplicationTests.java
    package org.ouyushan.springboot.data.mybatis;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    import org.ouyushan.springboot.data.mybatis.entity.UserInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
    
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @SpringBootTest
    @AutoConfigureMockMvc
    class SpringBootDataMybatisApplicationTests {
    
        /**
         * 根据ID查询
         */
        @Test
        public void testSelectById(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/api/user/getUser/{1}", 1))
                    .andDo(MockMvcResultHandlers.print()) //方法用于 打印请求、响应及其他相关信息
                    .andExpect(status().isOk())
                    .andExpect(content().json(("{"id":1,"userName":"admin","password":"123","age":28}")));
        }
    
        /**
         * 查询用户列表
         */
        @Test
        public void testSelectAll(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/api/user/getUsers"))
                    .andDo(MockMvcResultHandlers.print())
                    //.andDo(print())
                    .andExpect(status().isOk());
        }
    
    
        /**
         * 添加用户
         *
         * @throws Exception
         */
        @Test
        public void testAddUser(@Autowired MockMvc mockMvc) throws Exception {
    
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName("mockMvc1");
            userInfo.setPassword("mockmvc1");
            userInfo.setAge(24);
    
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(userInfo);
    
            mockMvc.perform(MockMvcRequestBuilders.post("/api/user/addUser")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(userJson))
    
                    .andDo(MockMvcResultHandlers.print())
                    // .andDo(print())
                    .andExpect(status().isOk());
        }
    
    
        /**
         * 更新用户
         *
         * @throws Exception
         */
        @Test
        public void testUpdateUser(@Autowired MockMvc mockMvc) throws Exception {
    
            UserInfo userInfo = new UserInfo();
            userInfo.setId(9L);
            userInfo.setUserName("mockMvc1");
            userInfo.setPassword("mockmvc1");
            userInfo.setAge(28);
    
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(userInfo);
    
            mockMvc.perform(MockMvcRequestBuilders.put("/api/user/updateUser")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(userJson))
    
                    .andDo(MockMvcResultHandlers.print())
                    // .andDo(print())
                    .andExpect(status().isOk());
        }
    
        /**
         * 删除
         *
         * @throws Exception
         */
        @Test
        public void testDeleteUser(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.delete("/api/user/delete/{id}", 9))
                    .andDo(MockMvcResultHandlers.print())
                    .andExpect(status().isOk());
        }
    }
  • 相关阅读:
    Visual Studio Ultimate 2012 RC win8 Metro应用的一个小bug样式继承
    windows 8 MSDN Examples 中一个奇怪的问题
    升级到IE9变成英文版的解决办法
    windows phone 中 TextBox 的诡异事件 TextChanged
    Windows Phone(OS7.1)中常用控件继承关系
    在Ubuntu使用gcc编译的程序无法运行的问题。
    Jquery实现简单图片切换
    div ul li 加a 错位问题
    asp.net mvc 2.0 数据验证
    asp.net mvc 2 (.net 4.0) “检测到有潜在危险的 Request.Form 值”的解决方法
  • 原文地址:https://www.cnblogs.com/ouyushan/p/13039145.html
Copyright © 2011-2022 走看看