1、配置文件

pom.xml

导入mybatis提供的启动器

 <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>

application.yml

spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
driver-class-name: com.mysql.cj.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Druid数据源配置:

package com.spboot.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; @Configuration
public class DruidConfig {
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid监控
//1.配置一个管理后台的servlet
@Bean
public ServletRegistrationBean StatViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<String ,String >();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认允许所有
initParams.put("deny","192.168.1.1");
bean.setInitParameters(initParams);
return bean;
} //2.配置一个web监控的filter
@Bean
public FilterRegistrationBean WebStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<String ,String >();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
} }

2、注解版

1、pojo类

package com.spboot.springboot.pojo;

public class Department {
private Integer id;
private String DepartmentName; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getDepartmentName() {
return DepartmentName;
} public void setDepartmentName(String departmentName) {
DepartmentName = departmentName;
}
}

2、新建Mybatis配置类

自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer

package com.spboot.springboot.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean; @MapperScan(value = "com.spboot.springboot.mapper")
@org.springframework.context.annotation.Configuration
public class MybatisConfig { @Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
} }; } }

如果使用@MapperScan(value = "com.spboot.springboot.mapper")注解,则会扫描mapper包下的所有mapper接口,也可以单独在mapper接口类中一一配置。

3、mapper接口

package com.spboot.springboot.mapper;

import com.spboot.springboot.pojo.Department;
import org.apache.ibatis.annotations.*; //告诉这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper { @Select("select * from department where id=#{id}")
public Department getDeptById(Integer id); @Delete("delete from department where id=#{id}")
public int deleteDepartmentById(Integer id); @Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(department_name) values(#{department_name})")
public int insertDepart(Department department); @Update("update department set department_name=#{department_name} where id=#{id}")
public int updateDept(Department department);
}

4、controller

@RestController
public class controller {
@Autowired
DepartmentMapper mapper; @RequestMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){ return mapper.getDeptById(id);
}
@RequestMapping("/dept")
public Department insertDepartment(Department department){
mapper.insertDepart(department);
return department; }
}

测试:

3、配置文件版

1、pojo

package com.spboot.springboot.pojo;

public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public Integer getGender() {
return gender;
} public void setGender(Integer gender) {
this.gender = gender;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Integer getdId() {
return dId;
} public void setdId(Integer dId) {
this.dId = dId;
}
}

2、mapper接口

package com.spboot.springboot.mapper;

import com.spboot.springboot.pojo.Employee;

//将接口扫描到容器中 @mapper
public interface EmployeeMapper { public Employee getEmpById(Integer id); public void insertEmpty(Employee employee);
}

3、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="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
<setting name="mapUnderscoreToCamelCase" value="true"/>启用从数据库列名A_COLUMN到驼峰式经典Java属性名aColumn的自动映射

4、EmployeeMapper.xml

mapper映射文件

<?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="com.spboot.springboot.mapper.EmployeeMapper"> <select id="getEmpById" resultType="com.spboot.springboot.pojo.Employee">
SELECT * FROM employee WHERE id = #{ID}
</select> <insert id="insertEmpty">
INSERT Into employee (lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{d_id})
</insert> </mapper>

注意关键一步:在application.yml加载mybaits配置文件包括(mybatis-config.xml和*Mapper.xml)

5、controller

  @Autowired
EmployeeMapper employeeMapper; @RequestMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}

测试:

ok 完成!

6_3.springboot2.x数据整合Mybatis(注解和非注解)的更多相关文章

  1. SpringBoot整合Mybatis多数据源 (AOP+注解)

    SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?xml version="1.0" encoding=& ...

  2. springMVC学习笔记(二)-----注解和非注解入门小程序

    最近一直在做一个电商的项目,周末加班,忙的都没有时间更新博客了.终于在上周五上线了,可以轻松几天了.闲话不扯淡了,继续谈谈springMvc的学习. 现在,用到SpringMvc的大部分使用全注解配置 ...

  3. 6_4.springboot2.x数据整合springData介绍

    介绍 Spring Data 项目的目的是为了简化构建基于Spring 框架应用的数据访问技术,包括非关系数据库.Map-Reduce 框架.云数据服务等等:另外也包含对关系数据库的访问支持. spr ...

  4. SpringMVC中注解和非注解方式下的映射器和适配器总结

    1. 非注解方式 1.1 处理器适配器 上一节中使用的处理器适配器是:org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapte ...

  5. 【SpringMVC学习03】SpringMVC中注解和非注解方式下的映射器和适配器总结

    从上一篇的springmvc入门中已经看到,springmvc.xml中的配置了映射器和适配器,是使用非注解的方式来配置的,这是非注解方式的一种,这里再复习一下: 1. 非注解方式 1.1 处理器适配 ...

  6. Springboot使用Cookie,生成cookie,获取cookie信息(注解与非注解方式)

    先 创建一个控制类吧, 其实我没有分层啊,随便做个例子: MyGetCookieController: @RestControllerpublic class MyGetCookieControlle ...

  7. 6_5.springboot2.x数据整合springData JPA

    1.配置文件 pom.xml <dependencies> <dependency> <groupId>org.springframework.boot</g ...

  8. springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)

    一.注解方式 pom <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId& ...

  9. springboot2.0+mysql整合mybatis,发现查询出来的时间比数据库datetime值快了8小时

    参考:https://blog.csdn.net/lx12345_/article/details/82020858 修改后查询数据正常

随机推荐

  1. 使用EditPlus批量修改文件编码格式

    步骤一: 步骤二: 步骤三: 步骤四:

  2. SpringMVC 拦截器原理

    前言 SpringMVC 拦截器也是Aop(面向切面)思想构建,但不是 Spring Aop 动态代理实现的, 主要采用责任链和适配器的设计模式来实现,直接嵌入到 SpringMVC 入口代码里面. ...

  3. Android Activity XML配置

    <activity android:name="xxxActivity" android:configChanges="keyboard|keyboardHidde ...

  4. js的线程和同步异步以及console.log机制

    项目上线了,闲下来就写写东西吧.积累了好多东西都没有做笔记~挑几个印象深刻的记录一下吧. js的同步异步以及单线程问题: 都知道单线程是js的一大特性.但是通常io(ajax获取服务器数据).用户/浏 ...

  5. csp-s模拟测试92

    csp-s模拟测试92 关于$T1$:最短路这一定建边最短路. 关于$T2$:傻逼$Dp$这一定线段树优化$Dp$. 关于$T3$:最小生成树+树P+换跟一定是这样. 深入(?)思考$T1$:我是傻逼 ...

  6. FZU - 2295 Human life:网络流-最大权闭合子图-二进制优化-第九届福建省大学生程序设计竞赛

    目录 Catalog Solution: (有任何问题欢迎留言或私聊 && 欢迎交流讨论哦 http://acm.fzu.edu.cn/problem.php?pid=2295 htt ...

  7. hexo next主题深度优化(七),cdn加速。

    文章目录 注: 正题: 免费cdn 收费cdn 个人博客:https://mmmmmm.me 源码:https://github.com/dataiyangu/dataiyangu.github.io ...

  8. spark-submit 应用程序第三方jar文件

    第一种方式:打包到jar应用程序 操作:将第三方jar文件打包到最终形成的spark应用程序jar文件中 应用场景:第三方jar文件比较小,应用的地方比较少 第二种方式:spark-submit 参数 ...

  9. IntelliJ IDEA创建springboot项目

    1.创建新项目. 2. 3.Group 是包名,Artifact是项目名. 4.springboot版本尽量选择最高版本,且不要选择SNAPSHOP版本. 5.路径可自定义,默认为D://IDEA/M ...

  10. 【POJ】3660 Cow Contest

    题目链接:http://poj.org/problem?id=3660 题意:n头牛比赛,有m场比赛,两两比赛,前面的就是赢家.问你能确认几头牛的名次. 题解:首先介绍个东西,传递闭包,它可以确定尽可 ...