SpringBoot与mybatis整合的一个小项目(附全部代码)

项目文件结构:
在这里插入图片描述

详细流程

1、引入Mybatis

我们使用 IDEA 建立一个 SpringBoot 项目,初始化组件部分选择 Web、JDBC API、MyBatis Framework、MySQL Drive。
项目初始化完成之后,可以在 pom.xml 文件中看到如下依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-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.3</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>

2、创建程序目录

我们在 com.example 目录下新建四个目录,分别是 controller、dao、entity、service。

  • controller层负责具体的业务模块流程的控制
  • entity层用于存放我们的实体类,与数据库中的属性值基本保持一致,实现set和get的方法
  • dao层主要是做数据持久层的工作,负责与数据库联络,封装了增删改查基本操作
  • service层主要负责业务模块的逻辑应用设计,具体要调用到已定义的DAO层的接口
  • 在 resource 目录下新建 mapper 目录。这个 mapper 目录是用来存放 SQL 语句的地方。

顺便提一下,我们知道的 MVC 框架,即 model-view-controller 三层架构。这里 model层等于entity层,与数据库的数据表对应,view层和 controller层结合非常紧密,需要联合起来一起开发。可以简单理解为 view层是做前端界面的展示,controller层做业务模流程块的控制。
如果在网上看到有 mapper层这个概念,就记住,mapper层=dao层,就是对数据库进行数据持久化操作。
不管是什么框架,我们很多时候都会与数据库进行交互。如果遇到一个场景我们都要去写SQL语句,那么我们的代码就会很冗余。所以,我们就想到了把数据库封装一下,让我们的数据库的交道看起来像和一个对象打交道,这个对象通常就是DAO。当我们操作这个对象的时候,这个对象会自动产生SQL语句来和数据库进行交互,我们就只需要使用DAO就行了。
通常我们在DAO层里面写接口,里面有与数据打交道的方法。SQL语句通常写在mapper文件里面的。
Service层是建立在DAO层之上的,建立了DAO层后才可以建立Service层,而Service层又是在Controller层之下的,因而Service层应该既调用DAO层的接口,又要提供接口给Controller层的类来进行调用,它刚好处于一个中间层的位置。每个模型都有一个Service接口,每个接口分别封装各自的业务处理方法。

3、理解后台访问流程

在这里插入图片描述
用户从页面前端,也就是我们所说的 view 层进行查询访问,进入到 controller 层找到对应的接口,接 着 controller 进行对 service 层进行业务功能的调用,service 要进入 dao 层查询数据,dao 层调用 mapper.xml 文件生成 sql 语句到数据库中进行查询。
在数据库中查询到数据,dao 层拿到实体对象的数据,接着交付给 service 层,接着 service 进行业务 逻辑的处理,返回结果给 controller,controller 根据结果进行最后一步的处理,返回结果给前端页 面。
创建一个访问用户信息的流程为:entity->dao->mapper->service->controller,这里 mapper 指的是存放 SQL 语句的 xml 文件。

4、核心文件配置

这里我们可以使用 application.properties 文件,也可以使用 application.yml 文件来进行配置,当然推荐使用 application.yml 文件。

如果用 application.yml 在第一次启动项目的时候报错,项目右侧 maven -> lifecycle -> clean一下即可。

server:
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/coffee?useUnicode=true & characterEncoding=utf-8 &
      useSSL=true & serverTimezone=Asia/Shanghai
    username: root
    password: ********

mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.learn.coffee.entity

5、编写entity

我们在编写entity时遵循POJO的思想。

这里需要提及“POJO最小侵入性编程”的概念,POJO(Plain Ordinary Java Object)意思是普通Java对象。类的成员是私有的,且有一系列的 setter and getter方法来提供访问。

POJO的内在含义是指那些没有从任何类继承、也没有实现任何接口,更没有被其它框架侵入的java对象。POJO的格式是用于数据的临时传递,它只能装载数据,作为数据存储的载体,而不具有业务逻辑处理的能力。

一般来讲,是 entity 中要取的数据应该和数据表相对应,但不一定要全部取出。

我们在刚才建立的 entity 目录中新建 Coffee 类,定义属性。

public class Coffee {
    private int coffeeId;
    private String coffeeName;
    private String coffeeKinds;
    private String coffeeDiscount;
    private int newPrice;
    private int oldPrice;
    private String coffeeImage;

    public int getCoffeeId() {
        return coffeeId;
    }

    public void setCoffeeId(int coffeeId) {
        this.coffeeId = coffeeId;
    }

    public String getCoffeeName() {
        return coffeeName;
    }

    public void setCoffeeName(String coffeeName) {
        this.coffeeName = coffeeName;
    }

    public String getCoffeeKinds() {
        return coffeeKinds;
    }

    public void setCoffeeKinds(String coffeeKinds) {
        this.coffeeKinds = coffeeKinds;
    }

    public String getCoffeeDiscount() {
        return coffeeDiscount;
    }

    public void setCoffeeDiscount(String coffeeDiscount) {
        this.coffeeDiscount = coffeeDiscount;
    }

    public int getNewPrice() {
        return newPrice;
    }

    public void setNewPrice(int newPrice) {
        this.newPrice = newPrice;
    }

    public int getOldPrice() {
        return oldPrice;
    }

    public void setOldPrice(int oldPrice) {
        this.oldPrice = oldPrice;
    }

    public String getCoffeeImage() {
        return coffeeImage;
    }

    public void setCoffeeImage(String coffeeImage) {
        this.coffeeImage = coffeeImage;
    }
}

6、编写dao

@Repository注解修饰哪个类,则表明这个类具有对对象进行CRUD(增删改查)的功能。

而且@Repository是@Component注解的一个派生品,所以被@Repository注解的类可以自动的被@ComponentScan 通过路径扫描给找到。因此@Repository注解的类也能@Autowired实现自动装配。

@Repository
public interface CoffeeDao {

    public List<Coffee> selectAllCoffee();

    public Coffee selectOneCoffee(@Param("coffeeId")int coffeeId);
}

我们推荐使用 @Param 进行传参,当映射器方法需要多个参数时,这个注解可以被用于:给映射器方法中的每个参数来取一个名字。这里有两点好处:

  1. 在 xml 文件中不需要再指定参数类型 parameterType
  2. 当传递对象时,使用 #{对象.属性} 可以更清晰地提示自己

如果不使用 @Param,多参数将会以它们的顺序位置和SQL语句中的表达式进行映射,这是默认的。

dao 层定义了接口,不需要写具体的实现类,我们只需要在 mapper 中将文件路径映射好就行了。 DAO的实现原理:它是通过JDK动态代理方式实现的,我们在启动加载配置文件的时候,它会根据 mapper 的 xml文件去生成一个DAO的实现。

使用配置文件版时,我们还需要在主程序中通过使用@MapperScan可以指定要扫描的Mapper类的包的路径。

7、编写Mapper

编写 Mapper.xml 文件主要注意三点:

  • namespace相对应
  • id相对应
  • resultType相对应

目前我们所讲的 resultType 返回单一类型的值,包括基础类型 String、Integer、Long,还有定义好的 Class 对象。
resultMap 则可以返回多个类型的值,适合多表连接查询。resultMap 的具体用法可以去官方文档中学习,这里我们不做过多的了解。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.learn.coffee.dao.CoffeeDao">

    <select id="selectAllCoffee" resultType="Coffee">
        select  * from coffee
    </select>

    <select id="selectOneCoffee" resultType="Coffee">
        select * from coffee where coffeeId=#{coffeeId}
    </select>
</mapper>

8、编写Service

我们需要在实现类中使用 @Service 注解,才能被 SpringBoot 扫描,在 Controller 中使用 @Autowired 注入

在 service 目录中新建 CoffeeService 类

@Service("CoffeeService")
public class CoffeeService {

    @Autowired
    private CoffeeDao coffeeDao;

    public List<Coffee> selectAllCoffee(){
        return coffeeDao.selectAllCoffee();
    }

    public Coffee selectOneCoffee(int coffeeId){
        return coffeeDao.selectOneCoffee(coffeeId);
    }

}

9、编写Controller

在 controller 目录中新建 CoffeeController 类

这里我们使用 Restful 风格,直接返回数据。

使用 @Autowired 注解自动装配 CoffeeService。编写接口为 CoffeeService 传输数据

@RestController
public class CoffeeController {

    @Autowired
    private CoffeeService coffeeService;

    @RequestMapping("/selectAllCoffee")
    public List<Coffee> selectAllCoffee(){
        return coffeeService.selectAllCoffee();
    }

    @RequestMapping("/selectOneCoffee")
    public Coffee selectOneCoffee(int coffeeId){
        return coffeeService.selectOneCoffee(coffeeId);
    }

}

10、运行项目

@MapperScan("com.learn.coffee.dao")
@SpringBootApplication
public class CoffeeApplication {

    public static void main(String[] args) {
        SpringApplication.run(CoffeeApplication.class, args);
    }

}

运行上面的方法,然后再浏览器的地址上输入:

http://127.0.0.1:8080/selectAllCoffee
http://127.0.0.1:8080/selectOneCoffee?coffeeId=1

运行结果:

在这里插入图片描述

在这里插入图片描述
到这一步,整个的后台访问流程就全部打通了,大家仔细理解其中的逻辑,多多揣摩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值