美文网首页
在Spring Boot中使用Mybatis

在Spring Boot中使用Mybatis

作者: 陆小愤 | 来源:发表于2018-11-12 22:34 被阅读0次

    最近在网易云课堂上看一些视频,给大家推荐一个讲Spring Boot的视频https://study.163.com/course/courseMain.htm?courseId=1005213034,老师讲的很不错。在学习的时候我也会做一些笔记,方便日后巩固。
    对这个系列感兴趣的可以看我之前写的博客:

    开始一个最简单的RESTful API项目

    RestController详解(上)

    RestController详解(下)

    这章会讲到用Mybatis连接数据库方面的知识。在连接数据库后,程序的层次会变得更加的复杂。所以在学习如何使用Mybatis之前,介绍一下程序的层次结构是非常有必要的。

    后端程序的层次结构

    在使用Spring的时候,我们经常会看到这几个注解:

    • @Controller @RestController
    • @Service
    • @Repository
    • @Component

    这些注解提供的功能都是相似的,即提供构建。使用了这些注解的类都可以使用@AutoWired进行装载。实际上这些注解就是根据程序的层次来划分的。


    程序的结构

    Spring的这些注解对应了程序的各个结构,正确的使用能让程序的可读性更好。
    划分了层次之后会有一个新的问题,就是如何分包?目前有两种观点,一是按层次划分,另一种是按功能划分:


    14.2

    博主自己更喜欢按层次划分,清楚一些。在视频中老师讲的例子也是按照层次划分的。

    不同层级之间的数据传输

    分层之后,各个类会互相调用,这时会涉及到参数之间的传递问题。这里主要有两种做法,一种是传递基本数据格式,另一种则是将这些数据封装成一个类,传递这个类的对象。这两种方式对比,很明显是第二种方法更清晰,可读性更高。


    15.1

    参数传递的对象会有不同的称呼,这些称呼每个都有不同的涵义,我们挨个来看一下:

    • PO = Persistant Object 持久对象,一般用于数据访问层,将这些对象持久的保存在数据库里面
    • DTO = Dta Transfer Object 数据传输对象,如果程序需要和外界通信,最外层一般是DTO
    • VO = Value Object(层级之间传递的对象)或View Object(MVC中使用)
    • POJO = Pure Old Java Object
    • DO = Domain Object = BO = Bussiness Object 处理业务逻辑
    • DAO = Data Access Object 用于处理和数据库之间的CRUD

    在以上列的几种object中,可以将它们分为两类:一种是PO,DTO,VO和POJO,它们实际上都是POJO,只有一些简单的属性;第二种是DO和DAO,这些就更复杂一些。

    还有一种是JavaBean,它有以下几个特点:

    • 有一个public的无参数建构方法
    • 属性private,且可以通过get、set、is(可以替代get,用在布尔型属性上)方法或遵循特定命名规范的其他方法访问
    • 可序列化,实现Serializable接口

    只要符合这三个特征的,就都是JavaBean。下面来说一说POJO与JavaBean的区别。

    POJO vs. JavaBean

    • POJO比javabean更简单。POJO严格地遵守简单对象的概念,而一些JavaBean中往往会封装一些简单逻辑。
    • POJO主要用于数据的临时传递,它只能装载数据, 作为数据存储的载体,不具有业务逻辑处理的能力。
    • Javabean虽然数据的获取与POJO一样,但是javabean当中可以有其它的方法

    现在我们来看几个具体的例子:

    1. 这是个POJO的例子。它的属性都是私有的,并有对应的getter,setter方法,符合POJO的特点。
      public class GradeClass {
        private String id;
        private String name;
        private List<Student> students;
      
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public List<Student> getStudents() {
            return students;
        }
        public void setStudents(List<Student> students) {
            this.students = students;
        }
      }
      
    2. 在上面的例子中,将getStudent()方法做了一些改进:首先是继承了Serializable接口;然后是在获取list之前先做了一个判断。这里有了一些简单的业务逻辑,符合JavaBean的要求,所以这个类是一个JavaBean。
      public class GradeClass implements Serializable {
        private String id;
        private String name;
        private List<Student> students;
      
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public List<Student> getStudents() {
            //如果学生列表为空,去数据库内查询该班级学生列表 
            if(students == null) {
                StudentDao dao = DaoFactory.getStudentDao();
                students = dao.getStudentsByGradeClassId(this.id);
            }
            return students;
        }
        public void setStudents(List<Student> students) {
            this.students = students;
        }
      }
      

    会判断了这些对象以后,我们再来看看它们都是在什么地方被用到的。


    15.2

    在Spring Boot项目中使用Mybatis

    这一节会在以前项目的基础上使用Mybatis连接数据库。在视频中老师使用的是PostgreSQL数据库,博主自己使用的是MySQL。如果要换成其他数据库只要添加相应的依赖。以下是建立数据库的SQL语句:

    create database tvseries;
    
    /**    TABLES      **/
    create table tv_series(
       id serial primary key,
       name varchar(50) not null,
       season_count int not null,
       origin_release date not null,
       status smallint not null default 0,
       delete_reason varchar(100) null
    );
    
    create table tv_character(
        id serial primary key,
        tv_series_id int not null,
        name varchar(50) not null,
        photo varchar(100) null
    );
    

    添加Mybatis支持步骤

    1. 修改pom.xml,添加mybatis和MySQL支持
      <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>1.3.1</version>
      </dependency>
    
      <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <!-- 5.1.46版本比较稳定-->
          <version>5.1.46</version>
      </dependency>
    
    
    1. 修改application.yml添加数据库连接
      spring:
        datasource:
          dbcp2.validation-query: select 1
          driverClassName: com.mysql.jdbc.Driver
          url: jdbc:mysql://localhost:3306/tvseries
          username: root
          password: root
    
    1. 修改application.yml添加让数据库中的下划线命名格式转为驼峰命名法的命令,方便编程(可选)
      mybatis:
        configuration:
          map-underscore-to-camel-case: true
    
    1. 在主目录下新建DAO包,用来储存DAO。修改启动类,在TestApplication类中增加@MapperScan(“package-of-mapping”)注解(很重要!不加注解程序就不能使用mybatis了)
      package cn.luxiaofen.test;
    
      import org.mybatis.spring.annotation.MapperScan;
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
    
      @MapperScan("cn.luxiaofen.test.Dao")
      @SpringBootApplication
      public class TestApplication {
    
          public static void main(String[] args) {
              SpringApplication.run(TestApplication.class, args);
          }
      }
    
    1. 将之前的Dto转为POJO(只需将TvSeriesDto的名字修改为TvSeries)。添加Mybatis Mapping,这里的DAO不需要建成类,用接口就可以。
      package cn.luxiaofen.test.Dao;
    
      import cn.luxiaofen.test.TvSeries;
      import org.apache.ibatis.annotations.Select;
      import org.springframework.stereotype.Repository;
    
      import java.util.List;
    
      @Repository
      public interface TvSeriesDao {
    
          //查询所有的记录
          @Select("select * from tv_series")
          public List<TvSeries> getAll();
      }
    
    1. 有了Dao,还应该有一个Service层,我们这里来写一个简单的service
      package cn.luxiaofen.test.Service;
    
      import cn.luxiaofen.test.Dao.TvSeriesDao;
      import cn.luxiaofen.test.TvSeries;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
    
      import java.util.List;
    
      @Service
      public class GetAllTvService {
          private final TvSeriesDao tvSeriesDao;
    
          @Autowired
          public GetAllTvService(TvSeriesDao tvSeriesDao) {
              this.tvSeriesDao = tvSeriesDao;
          }
    
          public List<TvSeries> getAllTvSeries() {
              return tvSeriesDao.getAll();
          }
      }
    
    1. 修改Controller中对应的方法
        private final GetAllTvService getAllTvService;
    
        @Autowired
        public TvSeriesController(GetAllTvService getAllTvService) {
            this.getAllTvService = getAllTvService;
        }
    
        @GetMapping
        public List<TvSeries> getAll() {
            if (log.isTraceEnabled()) {
                log.trace("getALL()被调用");
            }
    
            List<TvSeries> list = getAllTvService.getAllTvSeries();
    
            if (log.isTraceEnabled()) {
                log.trace("一共查询得到"+list.size()+"条记录");
            }
            return list;
        }
    
    1. 这样Mybatis的配置就完成了,在测试之前可以自行在数据库中加入几条数据。


      16.1

    项目结构图:

    16.2

    相关文章

      网友评论

          本文标题:在Spring Boot中使用Mybatis

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