Springboot下使用Mybatis

作者: 阿炎 | 来源:发表于2017-06-25 22:41 被阅读33次

    最近有项目需要使用java语言开发数据接口,整体框架需要符合微服务架构,在网上查找了相关资料,最终选定了Springcloud+Springboot的架构,此文主要记录Mybatis在Springboot下的使用,一方面作为学习日记,另一方面也希望对正在学习springboot的朋友们有一定帮助。
    全文包含3部分内容:

    • 项目搭建
    • 数据库配置
    • 数据操作层编写

    项目创建

    本文中使用的编辑器为Intellij Idea,创建流程也是基于Intellij,具体步骤如下:

    1. 在New Project面板中中选择Spring Initializr,点击Next按钮,如下图:


      image.png
    2. 填写项目的相关信息,Type一行根据使用习惯选择Maven或者Gradle就好。
    3. 选择项目的相关依赖,该文章中Web选项里选择了Web,Sql选项里面勾选Mybatis及Mysql后按着向导完成项目创建,如下图:


      image.png
    4. 最终生成的项目目录结构如下图:


      image.png
    5. 如下为项目的依赖配置文件代码:
    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.4.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </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>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    

    数据库配置

    在Springboot中,数据库的配置非常简单,在resources文件夹下的application.propertites编写相关配置即可,喜欢yml格式的也可以换成application.yml,具体如下:

    mybatis.type-aliases-package=com.aryan.entity
    
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    spring.datasource.username = root
    spring.datasource.password = demopc
    

    需注意第一行配置,com.aryan.entity指定了后面的mybatis数据库实体从哪个包进行查找。

    数据库操作层编写

    实体层编写

    1. 在main的src目录下新建package,命名为entity,作为mybatis的数据库实体层,与前面数据库配置相对应。
    2. 创建Product实体,代码如下:
    package com.aryan.entity;
    
    import java.io.Serializable;
    
    /**
     * Created by Aryan on 2017/6/25.
     */
    public class ProductEntity implements Serializable {
        private Long id;
        private String name;
        private String code;
    
        public ProductEntity() {
            super();
        }
        public ProductEntity(Long id, String name, String code) {
            super();
            this.id = id;
            this.name = name;
            this.code = code;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        @Override
        public String toString() {
            return "ProductEntity{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", code='" + code + '\'' +
                    '}';
        }
    }
    

    Dao层编写

    1. 在main目录的src文件夹下新建package,命名为mapper,该package作为项目的dao层映射,将sql语句与调用的方法关联起来,整体使用起来比较灵活。
    2. 在mapper包下新建ProductMapper接口,编写相关数据库操作方法,具体代码如下:
    package com.aryan.mapper;
    
    import com.aryan.entity.ProductEntity;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    /**
     * Created by Aryan on 2017/6/25.
     */
    public interface ProductMapper {
        @Select("SELECT * FROM products")
        List<ProductEntity> getAll();
    
        @Select("SELECT * FROM Products WHERE id = #{id}")
        ProductEntity getOne(Long id);
    
        @Insert("INSERT INTO products(name,code) VALUES(#{name}, #{code})")
        void insert(ProductEntity product);
    }
    
    
    

    控制器编写

    1. 在main目录src文件夹下新建package,命名为controller,该package作为MVC中的控制器,主要编写了产品添加及查询的路由,具体代码如下:
    package com.aryan.controller;
    
    import com.aryan.entity.ProductEntity;
    import com.aryan.mapper.ProductMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * Created by Aryan on 2017/6/25.
     */
    @RestController
    public class ProductController {
        @Autowired
        private ProductMapper productMapper;
    
        @RequestMapping(value = "/products")
        public List<ProductEntity> getAll() {
            return productMapper.getAll();
        }
    
        @RequestMapping(value = "/product/{id}")
        public ProductEntity getOne(@PathVariable Long id) {
            return productMapper.getOne(id);
        }
    
        @RequestMapping(value = "/product/add", method = RequestMethod.POST)
        public void insert(@RequestBody ProductEntity product) {
            productMapper.insert(product);
        }
    }
    
    

    运行项目

    1. 运行项目前首先需要在Application入口文件中加上dao层配置,添加@MapperScan("com.aryan.mapper")注解,代码如下:
    package com.aryan;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.aryan.mapper")
    public class SpringBootMybatisApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootMybatisApplication.class, args);
        }
    }
    
    1. 直接运行该项目, 运行成功后,在进行api访问时别忘记先把数据库表生成好, 然后访问http://localhost:8080/products 查看数据库数据,通过Postman或者Fiddler采用Post访问http://localhost:8080/product/add 并传递产品数据,成功后可以查看表数据确认接口是否运行正常。
      最后,整个项目完成后目录结构如下:
    image.png

    相关文章

      网友评论

        本文标题:Springboot下使用Mybatis

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