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 ...
随机推荐
- 【CQOI2008】中位数
题不难,但是思路有意思,这个是我自己想出来的OvO 原题: 给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b.中位数是指把所有元素从小到大排列后,位于中间的数. n<= ...
- CAM 查看里先选哪些层才能方便查看
CAM 检查 Gerber 时选 Layer 时有先后次序,才以看清楚是否有冲突. 比如检查 TOP 层时顺序应该是 MT ST L1 BOT 层检查顺序 MB SB L2/L4
- 【RAC】使用一条“ps”命令获取Linux环境下全部RAC集群进程信息
如何仅使用一条ps命令便能获取到所有与RAC集群进程相关的信息. 从所使用的命令角度上看很简单,仅需使用ps命令结合grep命令便能实现.问题关键是需要确定检索哪些关键字. 1.与RAC集群有关的进 ...
- 修改Nginx的header伪装服务器
有时候为了伪装自己的真实服务器环境.不像让对方知道自己的webserver真实环境,就不得不修改我们的webserer软件了!今天看了一下baidu.com的webserver感觉像是nginx修改的 ...
- WebClient类
WebClient类提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法. 其实就相当于创建一个请求客户端.可以获取网页和各种各样的信息,包括交互. 通过MSDN来看看WebC ...
- dzzoffice协同办公平台与onlyoffice在线协作平台安装与部署
1.安装dzzoffice协同办公平台 DzzOffice是一套开源办公套件,适用于企业.团队搭建自己的 类似“Google企业应用套件”.“微软Office365”的企业协同办公平台. 官网地址:h ...
- php中二维数组排序问题方法详解
PHP中二维数组排序,可以使用PHP内置函数uasort() 示例一: 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联 回调函数如下:注意回调函数的返回值是负数或者是false的时候,表示 ...
- 利用Python玩微信跳一跳
创建python项目jump_weixin,新建python程序jump.py 需要4个辅助文件[adb.exe,AdbWinApi.dll,AdbWinUsbApi.dll,fastboot.exe ...
- 转 WCF中同步和异步通讯总结
我这样分个类: WCF中, 以同步.异步角度考虑通讯的方式分为四种:跨进程同步.跨进程异步.发送队列端同步.发送队列端异步.之所以造成这样的结果源于两个因素,一个是传统概念上的同异步,一个是对于WCF ...
- 轻松理解execl系列函数
execl函数功能如下:启动一个可执行文件,并且对他进行传送参数.一些原型如下 #include <unistd.h> extern char **environ; int execl(c ...