SpringBoot+Mybatis整合实例
前言
大家都知道springboot有几大特点;能创建独立的Spring应用程序;能嵌入Tomcat,无需部署WAR文件;简化Maven配置;自动配置Spring等等。这里整合mybatis,创建一个简单的springboot实例。
创建一个springboot项目
按照以下步骤进行
注意:此处只选择web
这时,我们的项目就创建完成了,先测试一下
找到启动类,运行
地址栏查看
我们也可以通过window命令窗口启动
整合mybatis
看一下文件的目录结构以及作用
文件内容
maven依赖(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>nikeo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BootWeb</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.spring>4.3.14.RELEASE</version.spring>
<version.jackson>2.6.5</version.jackson>
<java.version>1.8</java.version>
<shiro.version>1.4.0</shiro.version>
<skiptests>true</skiptests>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.14</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
核心配置文件(application.properties)也可以命名成yml格式(application.yml)
server.port=8088
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sys?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.useGlobalDataSourceStat=true
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.thymeleaf.prefix = classpath:/static/
spring.thymeleaf.suffix = .html
配置文件(mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存-->
<setting name="cacheEnabled" value="true"/>
<!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 使用驼峰命名法转换字段-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="callSettersOnNulls" value="true"/>
<setting name="defaultStatementTimeout" value="25000" />
</settings>
</configuration>
Controller类
package com.example.nikeo.controller;
import com.example.nikeo.entity.Student;
import com.example.nikeo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by nikeodong on 2018/8/24.
*/
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/list")
public ResponseEntity<?> list(){
List<Student> student = studentService.list();
return ResponseEntity.ok(student);
}
}
Service类
package com.example.nikeo.service;
import com.example.nikeo.entity.Student;
import com.example.nikeo.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by nikeodong on 2018/8/24
*/
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public List<Student> list(){
return studentMapper.list();
}
}
映射类
package com.example.nikeo.mapper;
import com.example.nikeo.entity.Student;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by nikeodong on 2018/8/24
*/
@Repository
public interface StudentMapper {
List<Student> list();
}
映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.2//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.nikeo.mapper.StudentMapper">
<select id="list" resultType="Student">
SELECT * FROM student;
</select>
</mapper>
实体类
package com.example.nikeo.entity;
/**
* Created by nikeodong on 2018/8/24
*/
public class Student {
private Integer id;
private String name;
private String address;
private Integer age;
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
调整心跳类
package com.example.nikeo;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@MapperScan(basePackages = {"com.example.nikeo.mapper"})
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class BootWebApplication {
public static void main(String[] args) {
SpringApplication.run(BootWebApplication.class, args);
}
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("config/mybatis-config.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.example.nikeo.entity");
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
测试
SpringBoot+Mybatis整合实例的更多相关文章
- SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版)
SpringBoot Mybatis整合(注解版),SpringBoot集成Mybatis(注解版) ================================ ©Copyright 蕃薯耀 2 ...
- Springboot+Mybatis+MySQL实例练习时踩坑记录
最近刚开始学习后端,直接让上手学习Springboot+Mybatis+MySQL对CRUD的实例,虽然实例不难,但是上面的三个知识我都不懂,就有点为难我了 所以经常遇到一个点卡自己很久的情况,这里列 ...
- SpringBoot+Mybatis整合入门(一)
SpringBoot+Mybatis 四步整合 第一步 添加依赖 springBoot+Mybatis相关依赖 <!--springBoot相关--> <parent> < ...
- SpringBoot与Mybatis整合实例详解
介绍 从Spring Boot项目名称中的Boot可以看出来,SpringBoot的作用在于创建和启动新的基于Spring框架的项目,它的目的是帮助开发人员很容易的创建出独立运行的产品和产品级别的基于 ...
- 2、SpringBoot+Mybatis整合------一对一
开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis01/tree/93398da60c647573645917b2 ...
- springboot/Mybatis整合
正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: 1.5.6 jdk:1.8.0_161 maven:3.3.9 额外功能 PageHelper ...
- Springboot+Mybatis整合PageHelper
一.全部的gradle引入 // https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-sta ...
- springboot+mybatis整合(单元测试,异常处理,日志管理,AOP)
我用的事IDEA,jdk版本是1.7.新建项目的时候这个地方的选择需要注意一下,springboot版本是1.5的,否则不支持1.7的jdk pom.xml <dependency> &l ...
- 9、SpringBoot+Mybatis整合------动态sql
开发工具:STS 前言: mybatis框架中最具特色的便是sql语句中的自定义,而动态sql的使用又使整个框架更加灵活. 动态sql中的语法: where标签 if标签 trim标签 set标签 s ...
随机推荐
- asp:DropDownList与asp:DataList的联合使用
情况:当在asp:DropDownLis点击选取其中的一个值来响应datalist的值. <form id="form1" runat="server"& ...
- 51Nod 最大子矩阵和 | DP
Input 第1行:M和N,中间用空格隔开(2 <= M,N <= 500). 第2 - N + 1行:矩阵中的元素,每行M个数,中间用空格隔开.(-10^9 <= M[i] < ...
- [Luogu 2261] CQOI2007 余数求和
[Luogu 2261] CQOI2007 余数求和 这一定是我迄今为止见过最短小精悍的省选题了,核心代码 \(4\) 行,总代码 \(12\) 行,堪比小凯的疑惑啊. 这题一看暴力很好打,然而 \( ...
- c# 自定义排序Compare
.net FrameWork 框架博大精深,用着忘着,计划对自己能够想到知识点梳理一下,此篇是对自定义排序的理解: class Program { static void Main(string[] ...
- PHP把数据库数据导入Excel
<?php function xlsBOF() { echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); return; ...
- 【转载】Java JVM : Xms Xmx PermSize MaxPermSize 区别
转载自:http://cxh61207.iteye.com/blog/1160663 java JVM虚拟机选项: Xms Xmx PermSize MaxPermSize 区别 Xms 是指设定程 ...
- HDU 2553 N皇后问题 (深搜)
题目链接 Problem Description 在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上. 你的任务是,对 ...
- hdu 1162 Eddy's picture(最小生成树算法)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1162 Eddy's picture Time Limit: 2000/1000 MS (Java/Ot ...
- Perl6 Bailador框架(7):模版编写
先看一个例子: use v6; use Bailador; my $data = ' <form action="", method="get"> ...
- C 基础框架开发
引言 有的人真的是天命所归 延安时期炸弹 投到他院子都 没炸. 有些事无法改变 是命! 我们也快'老'了, 常回家看看. 前言 扯淡结束了,今天分享的可能有点多,都很简单,但是糅合在一起就是有点复杂. ...