Springboot下使用Mybatis

最近有项目需要使用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... 并传递产品数据,成功后可以查看表数据确认接口是否运行正常。
    最后,整个项目完成后目录结构如下:

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用MyBatis可以通过以下步骤实现: 1. 添加MyBatisMyBatis-Spring依赖 在pom.xml文件添加以下依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> ``` 2. 配置数据源 在application.properties文件配置数据源信息,例如: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root ``` 3. 配置MyBatis 在application.properties文件配置MyBatis相关信息,例如: ``` mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity ``` 4. 创建Mapper接口 创建Mapper接口,例如: ``` public interface UserMapper { User selectUserById(Integer id); } ``` 5. 创建Mapper XML文件 在resources/mapper目录下创建Mapper XML文件,例如: ``` <?xml version="1." encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.mapper.UserMapper"> <select id="selectUserById" resultType="com.example.demo.entity.User"> select * from user where id = #{id} </select> </mapper> ``` 6. 注入Mapper接口 在需要使用Mapper接口的地方注入Mapper接口,例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Integer id) { return userMapper.selectUserById(id); } } ``` 以上就是在Spring Boot使用MyBatis的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值