一、概述
1、Spring整合Mybatis步骤
第一步:导入相关jar包
junit;
mybatis;
mysql数据库;
spring相关;
aop织入;
mybatis-spring;
lombok;
log4j;
第二步:编写配置文件
第三步:测试
2、Mybatis使用步骤
第一步:编写实体类;
第二步:编写核心配置文件;
第三步:编写接口;
第四步:编写Mapper.xml;
第五步:测试;
二、环境搭建(Mybatis回顾)
第一步:新建Moudle,导入Maven坐标
<?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">
<parent>
<artifactId>StudySpring</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring_010_mybatis</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--Spring操作数据库的话,好需要Spring JDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
第二步:编写Account实体类
package com.zibo.pojo;
import lombok.Data;
@Data
public class Account {
private int id;
private String name;
private double money;
}
第三步:写查询接口
package com.zibo.mapper;
import com.zibo.pojo.Account;
import java.util.List;
public interface UserMapper {
List<Account> findAll();
}
第四步:创建映射配置文件
<?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.zibo.mapper.AccountMapper">
<!-- 配置查询所有-->
<select id="findAll" resultType="com.zibo.pojo.Account">
select * from account;
</select>
</mapper>
第五步:创建MyBatis的主配置文件
<?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">
<!--MyBatis的主配置文件-->
<configuration>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC">
</transactionManager>
<!--配置数据源,连接池-->
<dataSource type="POOLED">
<!--配置连接数据库的4个基本信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="zibo15239417242"/>
<property name="poolMaximumActiveConnections" value="20"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件是指每个dao独立的配置文件-->
<mappers>
<mapper resource="mapper/AccountMapper.xml"/>
</mappers>
</configuration>
第六步:写Log4j配置文件
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
第七步:写测试类MyTest
package com.zibo;
import com.zibo.mapper.AccountMapper;
import com.zibo.pojo.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
@Test
public void testFindAll() throws IOException {
//第一步:读取配置文件;
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//第二步:创建一个SqlSessionFactory工厂;
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//第三步:使用工厂生产SqlSession对象;
SqlSession session = factory.openSession();
//第四步:使用SqlSession对象创建接口的代理对象;
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
//第五步:使用代理对象执行方法;
List<Account> accounts = accountMapper.findAll();
for (Account account : accounts) {
System.out.println(account);
}
//第六步:释放资源
session.close();
in.close();
}
}
测试结果:
Account(id=1, name=大哥, money=100.0)
Account(id=2, name=二哥, money=200.0)
Account(id=6, name=訾博, money=88.0)
三、整合Mybatis方式一(重点)
1、mybatis-spring简介
什么是 MyBatis-Spring:
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring;
2、代码实现
第一步:在上面的环境搭建的项目里添加Spring配置文件applicationContext.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"
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">
<!--DataSource:使用Spring的数据源替换MyBatis的配置,c3p0 dbcp druid,
我们这里使用Spring的JDBC:org.springframework.jdbc.datasource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="zibo15239417242"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定Mybatis配置文件-->
<!--spring可以整合mybatis的配置,也可以将mybatis的配置文件引入-->
<!-- 这个引入导致错误,暂时就不引入了,所有的配置也可由spring完成-->
<!-- <property name="configuration" value="classpath:mybatis-config.xml"/>-->
<property name="mapperLocations" value="classpath:mapper/AccountMapper.xml"/>
<!-- 设置别名-->
<property name="typeAliasesPackage" value="com.zibo.pojo"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--这里只能通过构造器注入,因为SqlSessionTemplate没有setter方法-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!--注入AccountMapperImpl-->
<bean id="accountMapper" class="com.zibo.mapper.AccountMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
第二步:写一个AccountMapper的接口实现类
package com.zibo.mapper;
import com.zibo.pojo.Account;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class AccountMapperImpl implements AccountMapper {
//事情交友sqlSession完成
private SqlSessionTemplate sqlSession;
//给一个setter方法,适应setter注入
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<Account> findAll() {
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
return mapper.findAll();
}
}
第三步:修改测试类
package com.zibo;
import com.zibo.mapper.AccountMapper;
import com.zibo.pojo.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
@Test
public void testFindAll(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountMapper mapper = context.getBean("accountMapper", AccountMapper.class);
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}
测试结果:
Account(id=1, name=大哥, money=100.0)
Account(id=2, name=二哥, money=200.0)
Account(id=6, name=訾博, money=88.0)
四、整合Mybatis方式二(新)
第一步:再写一个AccountMapper的接口实现类
package com.zibo.mapper;
import com.zibo.pojo.Account;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class AccountMapperImpl2 extends SqlSessionDaoSupport implements AccountMapper {
@Override
public List<Account> findAll() {
return getSqlSession().getMapper(AccountMapper.class).findAll();
}
}
第二步:在applicationContext.xml中注册为bean
<?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"
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">
<!--DataSource:使用Spring的数据源替换MyBatis的配置,c3p0 dbcp druid,
我们这里使用Spring的JDBC:org.springframework.jdbc.datasource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="zibo15239417242"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定Mybatis配置文件-->
<!--spring可以整合mybatis的配置,也可以将mybatis的配置文件引入-->
<!-- 这个引入导致错误,暂时就不引入了,所有的配置也可由spring完成-->
<!-- <property name="configuration" value="classpath:mybatis-config.xml"/>-->
<property name="mapperLocations" value="classpath:mapper/AccountMapper.xml"/>
<!-- 设置别名-->
<property name="typeAliasesPackage" value="com.zibo.pojo"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--这里只能通过构造器注入,因为SqlSessionTemplate没有setter方法-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!--注入AccountMapperImpl-->
<bean id="accountMapper" class="com.zibo.mapper.AccountMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
<bean id="accountMapper2" class="com.zibo.mapper.AccountMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
第三步:修改测试类
package com.zibo;
import com.zibo.mapper.AccountMapper;
import com.zibo.pojo.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
@Test
public void testFindAll(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountMapper mapper = context.getBean("accountMapper2", AccountMapper.class);
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}
测试结果:
Account(id=1, name=大哥, money=100.0)
Account(id=2, name=二哥, money=200.0)
Account(id=6, name=訾博, money=88.0)