1. MyBatis概述
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
2. MyBatis原理
Mybatis——工作原理
实现了对Mapper接口对动态代理
对于SqlSessionTemplate的理解:(线程安全的实现类)
MyBatis-Spring(二)--SqlSessionTemplate实现增删改查:
3. Spring整合Mybatis
配置文件结构
1)pom.xml 依赖
<!-- 版本号 -->
<properties>
<servlet-version>3.0.1</servlet-version>
<jsp-version>2.2</jsp-version>
<jstl-version>1.2</jstl-version>
<spring-version>4.1.6.RELEASE</spring-version>
<aspectjweaver-version>1.8.6</aspectjweaver-version>
<mybatis-version>3.5.0</mybatis-version>
<mybatis-spring-version>2.0.0</mybatis-spring-version>
<log4j-version>1.2.17</log4j-version>
<mysql-connector-java-version>5.1.38</mysql-connector-java-version>
<jackson-version>2.8.5</jackson-version>
<commons-fileupload-version>1.3.1</commons-fileupload-version>
<poi-version>3.17</poi-version>
<hutool-version>4.5.9</hutool-version>
<version.shiro>1.2.2</version.shiro>
<gson-version>2.8.2</gson-version>
</properties>
<!-- 依赖 -->
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver-version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<!-- mybatis和spring整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring-version}</version>
</dependency>
<!-- log4j 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
<!-- commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<!-- mysql 驱动类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java-version}</version>
</dependency>
</dependencies>
2)web.xml SpringMVC控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 上下文参数 spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-aop.xml,
classpath:spring/spring*.xml,
</param-value>
</context-param>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 监听器-->
<listener>
<!-- 加载Spring默认配置文件 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- SpringMVC前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/springmvc.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--welcome-file-list>
<welcome-file>admin-user-password.html</welcome-file>
</welcome-file-list-->
</web-app>
3)spring-mybatis.xml 整合
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:myDB/db.properties"/>
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- SqlSessionFactory -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="neau.cekong.pojo"></property>
<property name="configLocation" value="classpath:myDB/mybatis-config.xml"></property>
</bean>
<!-- 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="neau.cekong.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
</beans>
4)spring-aop.xml 声明式事务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
<!-- 注解扫描 -->
<context:component-scan base-package="neau.cekong.**"></context:component-scan>
<!-- 代理方式 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
<!-- 事务管理器 -->
<bean id="txManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 声明式事务 -->
<tx:advice id="txAdvice" transaction-manager="txManage">
<tx:attributes>
<tx:method name="ins*"/><tx:method name="add*"/>
<tx:method name="del*"/>
<tx:method name="upd*"/><tx:method name="alt*"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<aop:pointcut expression="execution(* neau.cekong.service.impl.*.*(..))" id="mypoint"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
</aop:config>
</beans>
5)spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="neau.cekong.controller"></context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源 -->
<mvc:default-servlet-handler />
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
</beans>
6)log4j.properties
log4j.rootCategory=ERROR, CONSOLE ,LOGFILE
log4j.logger.neau.cekong.mapper=DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss} %m %n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%m %n
7)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>
<!-- 开启驼峰映射 ,为自定义的SQL语句服务-->
<!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="false"/>
</settings>
</configuration>
8)db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/FarmlandMonitor?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root
#注意更改包名!!!#
参考文章:
springmvc+mybatis的两种配置和应用方式
4. Spring-Boot整合Mybatis
数据库在开发过程中充当着重要的角色,框架的出现抹去了以往JDBC操作数据库的纷繁。传统的JDBC的数据库操作步骤为:①加载驱动 ②创建数据库连接 ③创建statement对象 ④执行SQL获取数据 ⑤数据转换 ⑥资源释放。而Mybatis关注第④步。于是在如此流行的后台框架Spring boot集成Mybatis也是大势所趋了。
1)Mybatis的集成可以简单地概括成两步:
①application.properties增加spring配置数据库链接地址
②pom.xml引入mybatis-spring-boot-starter和mysql-connector-java
spring boot+mybatis整合(使用配置好的启动器)
【SpringBoot2.0系列05】SpringBoot之整合Mybatis
springboot整合mybatis(步骤流畅)
mybatis最全教程之springboot集成mybatis(简洁)
Spring Boot(三)Spring Boot 和 MyBatis 整合(使用application.properties而不是yml)
SpringBoot 和 Mybatis 整合(腾讯云社区 清晰明了)
spring-boot 框架整合 MyBatis(简洁明了 结构清晰)
SpringBoot+Mybatis(JavaConfig方式配置)
springboot整合mybatis(SSM开发环境搭建 2种方式)
2)使用Config.java配置(传统方式)
1_ 项目结构
2_ db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/FarmlandMonitor?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root
3_ DataSourceConfiguration.java
package neau.cekong.weather.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
//这个注解导入刚才增加的jdbc配置文件
@PropertySource("classpath:db.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
4_ MyBatisConfig.java
package neau.cekong.weather.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource;
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "mySqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("neau.cekong.pojo");
try {
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
5_ MyBatisMapperScannerConfig.java
package neau.cekong.weather.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 扫描mybatis的接口
*/
@Configuration
// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//获取之前注入的beanName为sqlSessionFactory的对象
mapperScannerConfigurer.setSqlSessionFactoryBeanName("mySqlSessionFactory");
//指定xml配置文件的路径
mapperScannerConfigurer.setBasePackage("neau.cekong.weather.mapper");
return mapperScannerConfigurer;
}
}
参考文章:
https://www.cnblogs.com/zhuxiaojie/p/5836159.html#4278741