数据持久层框架MyBatis的应用

Posted 朵渔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据持久层框架MyBatis的应用相关的知识,希望对你有一定的参考价值。

1.引入依赖

 1 <parent>
 2     <groupId>org.springframework.boot</groupId>
 3     <artifactId>spring-boot-starter-parent</artifactId>
 4     <version>1.5.3.RELEASE</version>
 5   </parent>
 6 <dependency>
 7          <groupId>org.springframework.boot</groupId>
 8          <artifactId>spring-boot-starter-web</artifactId>
 9      </dependency>
10 
11      <dependency>
12          <groupId>io.springfox</groupId>
13          <artifactId>springfox-swagger-ui</artifactId>
14          <version>2.6.1</version>
15      </dependency>
16 
17      <dependency>
18          <groupId>io.springfox</groupId>
19          <artifactId>springfox-swagger2</artifactId>
20          <version>2.6.1</version>
21      </dependency>
22      <dependency>
23          <groupId>org.projectlombok</groupId>
24          <artifactId>lombok</artifactId>
25          <version>1.16.14</version>
26      </dependency>
27      <dependency>
28          <groupId>com.alibaba</groupId>
29          <artifactId>fastjson</artifactId>
30          <version>1.2.38</version>
31      </dependency>
32      <dependency>
33          <groupId>mysql</groupId>
34          <artifactId>mysql-connector-java</artifactId>
35      </dependency>
36      <dependency>
37          <groupId>org.mybatis.spring.boot</groupId>
38          <artifactId>mybatis-spring-boot-starter</artifactId>
39          <version>1.3.0</version>
40      </dependency>

2.编写application.yml配置文件,名称必须为application

 1 server:
 2    port: 8888 #指定启动端口号
 3 # 指定默认启动环境
 4 spring:
 5    application:
 6       name: test_service
 7    profiles:
 8       active: test # 默认环境
 9    datasource:
10        driver-class-name: com.mysql.jdbc.Driver
11        url: jdbc:mysql://127.0.0.1:3306/test
12        username: admin
13        password: admin123
14 
15 mybatis:
16     type-aliases-package: com.test.pojo #这里是实体类的位置,多个package用逗号或分号分隔
17     mapper-locations:
18        - mapper/*

3.mybatis-config.xml配置

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-com.course.config.dtd">
 5 
 6 <configuration>
 7     <typeAliases>
 8         <package name="com.test.pojo"/>
 9     </typeAliases>
10     <mappers>
11         <mapper resource="mapper/PeopleMapper.xml"/>
12     </mappers>
13 </configuration>

4.logback.xml配置

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <configuration
  3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4     xsi:noNamespaceSchemaLocation="http://www.padual.com/java/logback.xsd"
  5     debug="false" scan="true" scanPeriod="30 second">
  6 
  7     <property name="PROJECT" value="iorder" /> 
  8     <property name="ROOT" value="logs/${PROJECT}/" />
  9     <property name="FILESIZE" value="50MB" />
 10     <property name="MAXHISTORY" value="100" />
 11     <timestamp key="DATETIME" datePattern="yyyy-MM-dd HH:mm:ss" />
 12     <!-- 控制台打印 -->
 13     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
 14         <encoder charset="utf-8">
 15             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
 16             </pattern>
 17         </encoder>
 18     </appender>
 19     <!-- ERROR 输入到文件,按日期和文件大小 -->
 20     <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
 21         <encoder charset="utf-8">
 22             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
 23             </pattern>
 24         </encoder>
 25         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 26             <level>ERROR</level>
 27             <onMatch>ACCEPT</onMatch>
 28             <onMismatch>DENY</onMismatch>
 29         </filter>
 30         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 31             <fileNamePattern>${ROOT}%d/error.%i.log</fileNamePattern>
 32             <maxHistory>${MAXHISTORY}</maxHistory>
 33             <timeBasedFileNamingAndTriggeringPolicy
 34                 class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 35                 <maxFileSize>${FILESIZE}</maxFileSize>
 36             </timeBasedFileNamingAndTriggeringPolicy>
 37         </rollingPolicy>
 38     </appender>
 39     
 40     <!-- WARN 输入到文件,按日期和文件大小 -->
 41     <appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
 42         <encoder charset="utf-8">
 43             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
 44             </pattern>
 45         </encoder>
 46         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 47             <level>WARN</level>
 48             <onMatch>ACCEPT</onMatch>
 49             <onMismatch>DENY</onMismatch>
 50         </filter>
 51         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 52             <fileNamePattern>${ROOT}%d/warn.%i.log</fileNamePattern>
 53             <maxHistory>${MAXHISTORY}</maxHistory>
 54             <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 55                 <maxFileSize>${FILESIZE}</maxFileSize>
 56             </timeBasedFileNamingAndTriggeringPolicy>
 57         </rollingPolicy>
 58     </appender>
 59     
 60     <!-- INFO 输入到文件,按日期和文件大小 -->
 61     <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
 62         <encoder charset="utf-8">
 63             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
 64             </pattern>
 65         </encoder>
 66         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 67             <level>INFO</level>
 68             <onMatch>ACCEPT</onMatch>
 69             <onMismatch>DENY</onMismatch>
 70         </filter>
 71         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 72             <fileNamePattern>${ROOT}%d/info.%i.log</fileNamePattern>
 73             <maxHistory>${MAXHISTORY}</maxHistory>
 74             <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 75                 <maxFileSize>${FILESIZE}</maxFileSize>
 76             </timeBasedFileNamingAndTriggeringPolicy>
 77         </rollingPolicy>
 78     </appender>
 79     <!-- DEBUG 输入到文件,按日期和文件大小 -->
 80     <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
 81         <encoder charset="utf-8">
 82             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
 83             </pattern>
 84         </encoder>
 85         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 86             <level>DEBUG</level>
 87             <onMatch>ACCEPT</onMatch>
 88             <onMismatch>DENY</onMismatch>
 89         </filter>
 90         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 91             <fileNamePattern>${ROOT}%d/debug.%i.log</fileNamePattern>
 92             <maxHistory>${MAXHISTORY}</maxHistory>
 93             <timeBasedFileNamingAndTriggeringPolicy
 94                 class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 95                 <maxFileSize>${FILESIZE}</maxFileSize>
 96             </timeBasedFileNamingAndTriggeringPolicy>
 97         </rollingPolicy>
 98     </appender>
 99     <!-- TRACE 输入到文件,按日期和文件大小 -->
100     <appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
101         <encoder charset="utf-8">
102             <pattern>[%-5level] %d{${DATETIME}} [%thread] %logger{36} - %m%n
103             </pattern>
104         </encoder>
105         <filter class="ch.qos.logback.classic.filter.LevelFilter">
106             <level>TRACE</level>
107             <onMatch>ACCEPT</onMatch>
108             <onMismatch>DENY</onMismatch>
109         </filter>
110         <rollingPolicy
111             class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
112             <fileNamePattern>${ROOT}%d/trace.%i.log</fileNamePattern>
113             <maxHistory>${MAXHISTORY}</maxHistory>
114             <timeBasedFileNamingAndTriggeringPolicy
115                 class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
116                 <maxFileSize>${FILESIZE}</maxFileSize>
117             </timeBasedFileNamingAndTriggeringPolicy>
118         </rollingPolicy>
119     </appender>
120     
121     <!-- SQL相关日志输出-->
122     <logger name="org.apache.ibatis" level="INFO" additivity="false" />
123     <logger name="org.mybatis.spring" level="INFO" additivity="false" />
124     <logger name="com.github.miemiedev.mybatis.paginator" level="INFO" additivity="false" />
125     
126     <!-- Logger 根目录 -->
127     <root level="DEBUG">
128         <appender-ref ref="STDOUT" />
129         <appender-ref ref="DEBUG" />  
130         <appender-ref ref="ERROR" />
131         <appender-ref ref="WARN" />
132         <appender-ref ref="INFO" /> 
133         <appender-ref ref="TRACE" />
134     </root>
135 </configuration>

5.src下新建mapper包,包下新建PeopleMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 
 6 <mapper namespace="com.test">
 7     <select id="getPeopleCount" resultType="Integer">
 8         select count(*) from people;
 9     </select>
10 </mapper>

6.新建People实体类

 1 package com.test.pojo;
 2 
 3 import lombok.Data;
 4 
 5 @Data
 6 public class People {
 7     private int id;
 8     private String name;
 9     private int age;
10 }

7.新建com.test.controller包,包下新建Demo类,编写查询方法

 1 @Log4j
 2 @RestController
 3 @Api(value = "v1",description = "这是我的第一个版本的demo")
 4 @RequestMapping("v1")
 5 public class Demo {
 6     //首先获取一个执行sql语句的对象
 7 
 8     @Autowired
 9     private SqlSessionTemplate template;
10 
11     @GetMapping(value = "/getPeopleCount")
12     @ApiOperation(value = "可以获取到用户数")
13     public int getUserCount(){
14        return template.selectOne("getPeopleCount");
15     }
16 }

8.编写springboot启动类,运行

 1 package com.test;
 2 
 3 
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 import org.springframework.context.ConfigurableApplicationContext;
 7 import org.springframework.scheduling.annotation.EnableScheduling;
 8 
 9 import javax.annotation.PreDestroy;
10 
11 @EnableScheduling //开启计划任务的支持
12 @SpringBootApplication
13 public class Application {
14 
15     private  static ConfigurableApplicationContext context;
16 
17     public static void main(String[] args) {
18         Application.context = SpringApplication.run(Application.class,args);
19     }
20     //释放资源
21     @PreDestroy
22     public void close(){
23         Application.context.close();
24     }
25 
26 }

9.新增接口

9.1PeopleMapper.xml中配置

1 <insert id="insPeo">
2         insert into people values(#{id},#{name},#{age});
3     </insert>

9.2Demo中配置

1 @PostMapping("/addPeople")
2     @ApiOperation(value = "增加用户")
3     public int addPeople(@RequestBody People peo) {
4         return template.insert("insPeo",peo);
5     }

10.修改接口

10.1PeopleMapper.xml中配置

1 <update id="updPeo">
2         update people set name=#{name},age=#{age} where id=#{id};
3     </update>

10.2Demo中配置

1 @PostMapping("/updPeople")
2     @ApiOperation(value = "修改用户信息")
3     public int updPeople(@RequestBody People peo) {
4         return template.update("updPeo",peo);
5     }

11.删除接口

11.1PeopleMapper.xml中配置

1  <delete id="delPeo">
2         delete from people where id =#{id};
3     </delete>

11.2Demo中配置

1 @PostMapping("/delPeople")
2     @ApiOperation(value = "删除用户信息")
3     public int delPeople(@RequestBody People peo) {
4         return template.delete("delPeo",peo);
5     }

以上是关于数据持久层框架MyBatis的应用的主要内容,如果未能解决你的问题,请参考以下文章

持久层框架JPA与Mybatis该如何选型

优秀的持久层框架-Mybatis框架解析

优秀的持久层框架Mybatis,连接数据库快人一步

Mybatis学习之自定义持久层框架 为什么要用框架而不直接用JDBC?

MyBatisJava 持久层框架入门与实践 | 学习笔记

Java数据持久层框架 MyBatis之背景知识二