DEMO: springboot 与 mybatis 集成
之前一直在用springMVC,接触到springboot之后,感觉使用起来方便多了,没那多xml需要配置。
先来看看整个项目结构,当然是maven项目。

1、测试数据
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`sex` varchar(100) NOT NULL,
`no` int(100) NOT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('', 'danny', 'male', '', '2017-06-12 11:12:30', '2017-06-12 13:21:12');
INSERT INTO `student` VALUES ('', 'ellen', 'female', '', '2017-06-12 11:12:50', '2017-06-12 13:21:19');
2、pom.xml 文件
<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>learn.danny.yao</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M1</version>
</parent> <properties>
<java.version>1.8</java.version>
<mybatis.version>3.4.4</mybatis.version>
<druid.version>1.0.18</druid.version>
<mybatisSpring.version>1.3.0</mybatisSpring.version>
</properties> <dependencies>
<!--Spring Boot -->
<!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc。 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--支持使用 JDBC 访问数据库 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatisSpring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--Mysql / DataSource -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Json Support -->
<!-- <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId>
<version>1.1.43</version> </dependency> -->
<!--Swagger support -->
<!-- <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId>
<version>0.9.5</version> </dependency> --> <!-- 热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、springboot入口类 Application.java
package demo.springboot; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); public static void main(String[] args) {
SpringApplication.run(Application.class, args);
LOGGER.info("Springboot started successfully!");
}
}
4、Model类 Student.java
package demo.springboot.model;
import java.util.Date;
public class Student {
private Integer id;
private String name;
private String sex;
private Integer no;
private Date createTime;
private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
5、mapper类,StudentMapper.java
package demo.springboot.mapper;
import java.util.List;
import demo.springboot.model.Student;
public interface StudentMapper {
public List<Student> listStudents();
}
6、src/main/resources/mybatis/mapper/StudentMapper.xml
<?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="demo.springboot.mapper.StudentMapper" >
<resultMap id="BaseResultMap" type="demo.springboot.model.Student" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="no" property="no" jdbcType="INTEGER" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Base_Column_List" >
id, name, sex, no, create_time, update_time
</sql>
<select id="listStudents" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
</mapper>
7、service类,StudentService.java
package demo.springboot.service; import java.util.ArrayList;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import demo.springboot.mapper.StudentMapper;
import demo.springboot.model.Student; @Service
public class StudentService { @Autowired
private StudentMapper studentMapper; public List<Student> listStudents(){
List<Student> students = new ArrayList<>();
students = studentMapper.listStudents();
return students;
} }
8、mybatis配置类,主要配置DataSource和SqlSessionFactory。MybatisConfig.java
package demo.springboot.conf; import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.alibaba.druid.pool.DruidDataSourceFactory; /**
*
* @author danny.yao
* springboot集成mybatis基本入口
* 1、创建数据源
* 2、创建SqlSessionFactory
*/
@Configuration
@MapperScan(basePackages="demo.springboot.mapper")
public class MybatisConfig { @Autowired
Environment environment; /**
* 1、创建数据源
* @throws Exception
* @Primary该注解表示在同一个接口有多个类可以注入的时候,默认选择哪个,而不是让@Autowired报错
*/
@Bean
// @Primary
public DataSource getDataSource() throws Exception{
Properties properties = new Properties();
properties.put("driverClassName", environment.getProperty("jdbc.driverClassName"));
properties.put("url", environment.getProperty("jdbc.url"));
properties.put("username", environment.getProperty("jdbc.username"));
properties.put("password", environment.getProperty("jdbc.password"));
return DruidDataSourceFactory.createDataSource(properties);
} /**
* 2、根据数据源创建SqlSessionFactory
* @throws Exception
*/
@Bean
public SqlSessionFactory sessionFactory(DataSource dataSource) throws Exception{
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setTypeAliasesPackage(environment.getProperty("mybatis.typeAliasesPackage"));
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(environment.getProperty("mybatis.mapperLocations")));
return sessionFactoryBean.getObject();
} }
9、src/main/resources/application.properties 配置文件
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/test
jdbc.username = root
jdbc.password = test # mybatis #
mybatis.typeAliasesPackage=demo.springboot.model
mybatis.mapperLocations=classpath:/mybatis/mapper/*.xml
10、至此,文件就完整了,启动应用
Application.java类上 run as Java Application,启动应用。看到“Springboot started successfully!” 说明启动成功

11、测试
从浏览器访问 http://localhost:8080/student/list,查看日志看能否正常打印db返回的信息

DEMO: springboot 与 mybatis 集成的更多相关文章
- DEMO: springboot 与 freemarker 集成
直接在 DEMO: springboot 与 mybatis 集成 基础上,进行修改. 1.pom.xml 中引用 依赖 <dependency> <groupId>org.s ...
- Springboot 和 Mybatis集成开发
Springboot 和 Mybatis集成开发 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 jdk:1.7.0_79 maven:3.3.9 额外功能 PageHel ...
- springboot和mybatis集成
springboot和mybatis集成 pom <?xml version="1.0" encoding="UTF-8"?> <proje ...
- springboot和mybatis集成,自动生成model、mapper,增加mybatis分页功能
整体思路和http://www.cnblogs.com/mahuan2/p/5859921.html相同. 主要讲maven的pom.xml和一些配置变化,详细说明. 软件简介 Spring是一个流行 ...
- springboot与mybatis集成
1)添加依赖 <!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId& ...
- SpringBoot 整合 MyBatis,实现 CRUD 示例
目录 前言 创建项目/模块 SpringBoot Console Application CommandLineRunner SpringBoot 集成 MyBatis 创建数据库/表 配置数据源/连 ...
- SpringBoot框架与MyBatis集成,连接Mysql数据库
SpringBoot是一种用来简化新Spring应用初始搭建及开发过程的框架,它使用特定方式来进行配置,使得开发人员不再需要定义样板化的配置.MyBatis是一个支持普通SQL查询.存储和高级映射的持 ...
- Springboot 系列(十二)使用 Mybatis 集成 pagehelper 分页插件和 mapper 插件
前言 在 Springboot 系列文章第十一篇里(使用 Mybatis(自动生成插件) 访问数据库),实验了 Springboot 结合 Mybatis 以及 Mybatis-generator 生 ...
- spring-boot 速成(8) 集成druid+mybatis
spring-boot与druid.mybatis集成(包括pageHelper分页插件), 要添加以下几个依赖项: compile('mysql:mysql-connector-java:6.0.5 ...
随机推荐
- MySQL--查询表统计信息
============================================================= 可以用show table status 来查看表的信息,如:show ta ...
- 使用npm init快速创建web 应用
一般来说我们会有npm init -y 快速生成package.json 文件, 但是npm init 可以使用脚手架工具,生成项目,比较方便 参考 npm init 帮助命令 npm init [- ...
- ory Oathkeeper Ecosystem
ory Oathkeeper 生态包含的组件 ORY Hydra is an OAuth 2.0 and OpenID Connect provider. ORY Oathkeeper is an I ...
- C51 头文件中的 extern
C51 头文件使用 extern 的目的是声明外部变量或函数. 使用注意: 只放在 .h 文件中. 声明时不用赋值. extern 只是声明不是定义.
- DOMContentLoaded 和 Load 事件 区别(待补充)
javascript会阻塞dom的解析.当解析过程中遇到<script>标签的时候,便会停止解析过程,转而去处理脚本,如果脚本是内联的,浏览器会先去执行这段内联的脚本,如果是外链的,那么先 ...
- jsp 中变量作用域:pageScope、requestScope、sessionScope、applicationScope
jsp 中,变量的作用域,一共有4种: pageScope:表示变量只能在本页面使用. requestScope:表示变量能在本次请求中使用. sessionScope:表示变量能在本次会话中使用. ...
- hihocoder 1513 小Hi的烦恼——bitset
题目:http://hihocoder.com/problemset/problem/1513 自带的题解写得很好…… #include<cstdio> #include<cstri ...
- 百度地图JavaScript如何清除指定类型的覆盖物
由于一个地图中有很多种类型的覆盖物,由于某个覆盖物(一般是自定义)整个地图中只允许出现一次 那第一想到的就是,每次创建这个类型的覆盖物时先清除这一类型的覆盖物,比较简单判断覆盖物的类型 instanc ...
- ML(2): 术语及算法分类汇总
机器学习术语 归纳总结机器学习相关的基本术语,以一批西瓜的数据为例,例如:(色泽=青绿:根蒂=蜷缩:敲声=浊响),(色泽=乌黑:根蒂=稍蜷:敲声=沉闷),(色泽=浅白:根蒂=硬挺:敲声=清脆)... ...
- HttpClient连接池
HttpClient连接池,发现对于高并发的请求,效率提升很大.虽然知道是因为建立了长连接,导致请求效率提升,但是对于内部的原理还是不太清楚.后来在网上看到了HTTP协议的发展史,里面提到了一个属性C ...