MyBatis

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。

集成spring boot 的时候必须在mapper接口上面标注@Mapper注解

项目图片

pom.xml

-只需要在pom.xml引入需要的数据库配置,就会自动访问此数据库,如果需要配置其他数据库,可以在application.properties进行添加

-默认使用org.apache.tomcat.jdbc.pool.DataSource创建连接池

<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.jege.spring.boot</groupId>
<artifactId>spring-boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-mybatis</name>
<url>http://maven.apache.org</url> <!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath />
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies> <!-- 持久层 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency> <!-- h2内存数据库 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <build>
<finalName>spring-boot-mybatis</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

User.java

package com.jege.spring.boot.mybatis.entity;

/**
* @author JE哥
* @email 1272434821@qq.com
* @description:模型对象
*/
public class User {
private Long id;
private String name;
private Integer age; public User() { } public User(String name, Integer age) {
this.name = name;
this.age = age;
} 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 Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}

UserMapper.java

package com.jege.spring.boot.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import com.jege.spring.boot.mybatis.entity.User; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:持久层接口,由spring自动生成其实现
*/
@Mapper
public interface UserMapper {
@Delete("drop table t_user if exists")
void dropTable(); @Insert("create table t_user (id bigint generated by default as identity, age integer, name varchar(255), primary key (id))")
void createTable(); @Insert("insert into t_user(name,age) values(#{name},#{age})")
void insert(User user); @Select("select id,name,age from t_user")
List<User> findAll(); @Select("select id,name,age from t_user where name like #{name}")
List<User> findByNameLike(String name); @Delete("delete from t_user")
void deleteAll(); }

Application.java

package com.jege.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:spring boot 启动类
*/ @SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }

不需要application.properties

UserMapperTest.java

package com.jege.spring.boot.mybatis;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jege.spring.boot.mybatis.entity.User;
import com.jege.spring.boot.mybatis.mapper.UserMapper; /**
* @author JE哥
* @email 1272434821@qq.com
* @description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest()
public class UserMapperTest {
@Autowired
UserMapper userMapper; // 每次执行Test之前先删除表,创建表
@Before
public void before() throws Exception {
userMapper.dropTable();
userMapper.createTable();
} // 打印出class com.sun.proxy.$Proxy66表示spring注入通过jdk动态代理获取接口的子类
@Test
public void proxy() throws Exception {
System.out.println(userMapper.getClass());
} @Test
public void save() throws Exception {
for (int i = 0; i < 10; i++) {
User user = new User("jege" + i, 25 + i);
userMapper.insert(user);
}
} @Test
public void all() throws Exception {
save();
assertThat(userMapper.findAll()).hasSize(10);
} @Test
public void findByName() throws Exception {
save();
assertThat(userMapper.findByNameLike("jege%")).hasSize(10);
} // 每次执行Test之后清空数据
@After
public void destroy() throws Exception {
userMapper.deleteAll();
} }

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!



Spring Boot 系列教程3-MyBatis的更多相关文章

  1. Spring Boot 系列教程19-后台验证-Hibernate Validation

    后台验证 开发项目过程中,后台在很多地方需要进行校验操作,比如:前台表单提交,调用系统接口,数据传输等.而现在多数项目都采用MVC分层式设计,每层都需要进行相应地校验. 针对这个问题, JCP 出台一 ...

  2. Spring Boot 系列教程18-itext导出pdf下载

    Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ...

  3. Spring Boot 系列教程17-Cache-缓存

    缓存 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找.由于缓存的运行速度比内存快得多,故缓存的作用就是帮 ...

  4. Spring Boot 系列教程16-数据国际化

    internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...

  5. Spring Boot 系列教程15-页面国际化

    internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...

  6. Spring Boot 系列教程14-动态修改定时任务cron参数

    动态修改定时任务cron参数 不需要重启应用就可以动态的改变Cron表达式的值 不能使用@Scheduled(cron = "${jobs.cron}")实现 DynamicSch ...

  7. Spring Boot 系列教程12-EasyPoi导出Excel下载

    Java操作excel框架 Java Excel俗称jxl,可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件,现在基本没有更新了 http://jxl.sourcef ...

  8. Spring Boot 系列教程11-html页面解析-jsoup

    需求 需要对一个页面进行数据抓取,并导出doc文档 html解析器 jsoup 可直接解析某个URL地址.HTML文本内容.它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操 ...

  9. Spring Boot 系列教程10-freemarker导出word下载

    freemarker FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个 ...

  10. Spring Boot 系列教程9-swagger-前后端分离后的标准

    前后端分离的必要 现在的趋势发展,需要把前后端开发和部署做到真正的分离 做前端的谁也不想用Maven或者Gradle作为构建工具 做后端的谁也不想要用Grunt或者Gulp作为构建工具 前后端需要通过 ...

随机推荐

  1. POJ 2773 Happy 2006#素数筛选+容斥原理+二分

    http://poj.org/problem?id=2773 说实话这道题..一点都不Happy好吗 似乎还可以用欧拉函数来解这道题,但正好刚学了容斥原理和二分,就用这个解法吧. 题解:要求输出[1, ...

  2. 浅析const标识符在C++函数的功能

    范例: class matrix { public: matrix(){}; const double getvalue(const unsigned row, const unsigned colu ...

  3. 二分法经典习题——HDU1969

    #include <iostream>#include <cmath>#include <iomanip>using namespace std; double p ...

  4. 1bpp像素遍历(找了半天,感谢github)

    /// <summary> /// 获取比例 /// </summary> /// <param name="rect"></param& ...

  5. UISwitch 开关控件

    UISwitch iOS中的开关控件,只有两种状态,打开或关闭. aSwitch.tintColor = [UIColor redColor]; //关闭状态下的渲染颜色 aSwitch.onTint ...

  6. Python从json中提取数据

    #json string:s = json.loads('{"name":"test", "type":{"name": ...

  7. python [1:3]

    Python下标是以0开始的x[1:3]表示返回集合中下标1至3(不包括3)的元素集合x[:3] 表示返回从开始到下标3(不包括3)的元素集合x[3:]表示返回从下标3到结束的元素集合X[:]表示返回 ...

  8. Java操作*.properties

    java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properti ...

  9. 3. JavaScript 数据类型

    1. 主要类型 字符串(String).数字(Number).布尔(Boolean).数组(Array).对象(Object).空(Null).未定义(Undefined). JavaScript 拥 ...

  10. web开发路径问题

    1. web开发路径问题总结: http://www.cnblogs.com/tianguook/archive/2012/08/31/2665755.html 2. JSP/SERVLET 路径问题 ...