生活随笔
收集整理的這篇文章主要介紹了
玩转springboot:整合mybatis实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這篇文章講解一下springboot整合mybatis,其實,springboot整合mybatis和springmvc整合mybatis并沒有什么太大的區別,大體上還是差不多哦,只是比springmvc更加的簡單一點,下面我們就以一個例子來講解一下整合mybatis。
我們先看一下pom.xml
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version>
</dependency>
因為mybatis已經整合到starter中了,所以我們只需要引入這個依賴就可以了。
下面,我們以Employee員工為例
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer dId;//getter setter
}
//@Mapper或者@MapperScan將接口掃描裝配到容器中
@Mapper
public interface EmployeeMapper {@Select("select * from employee where id=#{id}")public Employee getEmpById(Integer id);@Insert("Insert into employee(email) values(#{email})")public void insertEmp(Employee employee);
}
上面這是以注解的方式進行配置,當然我們也可以使用配置文件
//@Mapper或者@MapperScan將接口掃描裝配到容器中
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee);
}
因為是配置文件版,所以我們需要配置mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sihai.springboot.mapper.EmployeeMapper"><!-- public Employee getEmpById(Integer id);public void insertEmp(Employee employee);--><select id="getEmpById" resultType="com.sihai.springboot.bean.Employee">SELECT * FROM employee WHERE id=#{id}</select><insert id="insertEmp">INSERT INTO employee(email) VALUES (#{email})</insert>
</mapper>
我們在看一下mybatis數據源的配置,我們這里使用yml的方式,數據源使用druid,配置如下
spring:datasource:
# 數據源基本配置username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://192.168.15.22:3306/mybatistype: com.alibaba.druid.pool.DruidDataSource
# 數據源其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true
# 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用于防火墻filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:# 指定全局配置文件位置config-location: classpath:mybatis/mybatis-config.xml# 指定sql映射文件位置mapper-locations: classpath:mybatis/mapper/*.xml
這就是mybatis整合springboot 的過程了,要了解mybatis的用法,請查看下面的文章mybatis系列文章
總結
以上是生活随笔為你收集整理的玩转springboot:整合mybatis实例的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。