一、前期准备
导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--Spring、MyBatis整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
Maven静态资源过滤问题
<!-- Maven由于“约定大于配置”,我们之后可能会遇到写的配置文件无法被导出或者生效的问题,解决方案如下: -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
回顾MyBatis
编写pojo实体类
package com.comprehensive.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
编写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">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf-8&useSSL=false&verifyServerCertificate=false&autoReconnect=true&autoReconnectForPools=true&allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="txq199807031578"/>
</dataSource>
</environment>
</environments>
<!-- 绑定接口 -->
<mappers>
<mapper class="com.comprehensive.dao.UserMapper"></mapper>
</mappers>
</configuration>
编写UserMapper接口
package com.comprehensive.dao;
import com.comprehensive.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getAllUsers();
}
编写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.comprehensive.dao.UserMapper">
<select id="getAllUsers" resultType="com.comprehensive.pojo.User">
select * from mybatis.user;
</select>
</mapper>
测试
package com.comprehensive.dao;
import com.comprehensive.pojo.User;
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;
public class UserMapper_Test {
@Test
public void test1() {
try {
String resources = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resources);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for(User user : mapper.getAllUsers()) System.out.println(user);
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、mybatis-spring
整合MyBatis之前需要了解mybatis-spring包中的一些重要类
SqlSessionFactoryBean
在 mybatis-spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中
<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
注意:SqlSessionFactory需要一个 DataSource(数据源)。这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。而在 myBatis-spring 中,则使用 SqlSessionFactoryBean 来创建
SqlSessionTemplate
SqlSessionTemplate 是 myBatis-spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession
<!--SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
注意:可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
SqlSessionTemplate 可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
三、整合MyBatis
方式一
配置数据源
<!--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/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf-8&useSSL=false&verifyServerCertificate=false&autoReconnect=true&autoReconnectForPools=true&allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="txq199807031578"/>
</bean>
配置SqlSessionFactory,关联MyBatis
<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--关联MyBatis-->
<!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->
<property name="mapperLocations" value="classpath:com/comprehensive/dao/UserMapper.xml"/>
<!--
<property name="mapperLocations" value="classpath*:com/comprehensive/dao/*.xml"/>
-->
</bean>
注意:配置SqlSessionFactory后,mybatis-config.xml配置文件中对应的配置信息也可以省略
配置SqlSession,关联SqlSessionFactory
<!--SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--关联SqlSessionFactory-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
编写Dao接口的实现类,私有化sqlSessionTemplate
package com.comprehensive.dao;
import com.comprehensive.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserDaoImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> getAllUsers() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.getAllUsers();
}
}
注册bean实现
<!--DaoImpl-->
<bean id="userDaoImpl" class="com.comprehensive.dao.UserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
测试
public class UserMapper_Test {
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper userMapper = (UserMapper) context.getBean("userDaoImpl");
for(User user : userMapper.getAllUsers()) System.out.println(user);
}
}
方式二
配置数据源
<!--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/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf-8&useSSL=false&verifyServerCertificate=false&autoReconnect=true&autoReconnectForPools=true&allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="txq199807031578"/>
</bean>
配置SqlSessionFactory,关联MyBatis
<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:com/comprehensive/dao/*.xml"/>
</bean>
编写Dao接口的实现类,继承SqlSessionDaoSupport类
package com.comprehensive.dao;
import com.comprehensive.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserDaoImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> getAllUsers() {
return getSqlSession().getMapper(UserMapper.class).getAllUsers();
}
}
注册bean实现
<!--DaoImpl-->
<bean id="userDaoImpl" class="com.comprehensive.dao.UserDaoImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
</bean>
测试
public class UserMapper_Test {
@Test
public void test3() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
UserMapper userMapper = context.getBean("userDaoImpl", UserMapper.class);
for(User user : userMapper.getAllUsers()) System.out.println(user);
}
}