回顾Mybatis
一、编写实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
二、编写实体类接口
//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
//编写针对User表的相关操作,现在是查询用户
public List<User> selectUser();
}
三、编写实体类接口对应的xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
<select id="selectUser" resultType="user" parameterType="map">
select * from mybatis.user
<where>
<if test="id !=null">
id = #{id}
</if>
</where>
</select>
</mapper>
四、编写Mybatis工具类
//Mybatis工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//引入Mybatis核心配置文件路径
String resource = "mybatis-config.xml";
//通过Resources类读取核心配置文件,变成输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactoryBuilder对象,调用build方法创建sqlSessionFactory对象,专门用来开启sqlSession
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//通过sqlSessionFactory工厂,开启sqlSession
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
五、编写核心配置文件mybatis-config.xml,注册Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!-- 给实体类设置别名,用包扫描的方式,在这个包下面的实体类都默认别名为类名首字母小写-->
<typeAliases>
<package name="com.guohui.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<!-- transactionManager表示事务管理-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 在mybatis配置文件中的&符号要先进行转义,用&-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&characterEncoding=utf8&useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.xml文件都需要在我们的Mybatis核心配置文件中进行注册-->
<mappers>
<mapper resource="com/guohui/mapper/UserMapper.xml"/>
</mappers>
</configuration>
六、测试
public class MyTest {
@Test
public void test(){
//获取SqlSession实例
SqlSession sqlSession = MybatisUtils.getSqlSession();
//获取接口类,这样就可以直接调用接口中的方法
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user : users) {
System.out.println(user);
}
//会话结束,关闭sqlSession
sqlSession.close();
}
}
七、控制台
整合方式一
一、整合之前先在pom.xml中导入依赖
一定注意:导包一定要导版本适合的,不然不兼容,后面测试的时候就会报错
<dependencies>
<!-- 将Mybatis整合到Spring,先导包-->
<!-- 导入测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 导入数据库连接依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- Mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!-- spring-webmvc支持Spring功能依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- AOP织入依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- Spring操作数据库,需要导入的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- 整合Mybatis到Spring导入这个依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- 导入Lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
<!--配置resources,防止资源导出失败-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
二、编写spring-dao.xml配置文件(编写数据源、sqlSessionFactory、sqlSessionTemplate) 和mybatis-config.xml配置文件
1、spring-dao.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据源DataSource:使用Spring的数据源替换掉Mybatis中的配置,
我们现在使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
这里我们能导入是因为我们pom.xml中导入了spring-jdbc的依赖-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&characterEncoding=utf8&useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置sqlSessionFactory,将数据源通过set方法注入到sqlSessionFactory中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定Mybatis配置文件,name是写死的用configLocation,作用是将这个配置文件和mybatis-config.xml关联-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 配置注册Mapper.xml文件-->
<property name="mapperLocations" value="classpath:com/guohui/mapper/*.xml"/>
</bean>
<!-- SqlSessionTemplate:就是我们mybatis中使用的sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 将sqlSessionFactory使用有参构造器注入到SqlSessionTemplate中,因为SqlSessionTemplate类中没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
2、mybatis-config.xml配置文件,此时已经和spring-dao.xml关联
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!-- 给实体类设置别名,用包扫描的方式,在这个包下面的实体类都默认别名为类名首字母小写-->
<typeAliases>
<package name="com.guohui.pojo"/>
</typeAliases>
<!--将来养成习惯,在Mybatis核心配置文件中仅仅配置别名还有一些setting设置即可-->
<!-- <settings>-->
<!-- <setting name="" value=""/>-->
<!-- </settings>-->
</configuration>
三、编写实体类、实体类接口、Mapper.xml文件,另外需要给接口增加实现类
1、实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
2、实体类接口
//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
//编写针对User表的相关操作,现在是查询用户
public List<User> selectUser(Map map);
}
3、Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
<select id="selectUser" resultType="user" parameterType="map">
select * from mybatis.user
<where>
<if test="id !=null">
id = #{id}
</if>
</where>
</select>
</mapper>
4、接口实现类
public class UserMapperImpl implements UserMapper{
//现在我们使用SqlSessionTemplate取代了sqlSession
private SqlSessionTemplate sqlSession;
//编写set方法,便于在spring-dao.xml配置文件中用set方法注入Bean
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
//现在我们将Mybatis和Spring进行整合以后,直接调用方法,就能直接实现对数据库的操作
@Override
public List<User> selectUser(Map map) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser(map);
}
}
四、编写一个applicationContext.xml核心配置文件,将来的Dao或者MVC的配置文件都可以通过import关键字来导入,注册我们编写的实现类
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 导入Dao配置文件-->
<import resource="spring-dao.xml"/>
<!-- 注册UserMapperImpl.java实现类-->
<bean id="sqlSession" class="com.guohui.mapper.UserMapperImpl">
<!-- 将SqlSessionTemplate类型的sqlSession通过set方法注入到UserMapperImpl实现类中-->
<property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>
</beans>
五、测试
public class MyTest {
@Test
public void test(){
//获取Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//我们现在只需要创建UserMapperImpl实现类的对象,调用里面的方法即可,注意,最后的类型要是接口的类型
UserMapper sqlSession = context.getBean("sqlSession", UserMapper.class);
Map<Object, Object> map = new HashMap();
map.put("id",1);
for (User user : sqlSession.selectUser(map)) {
System.out.println(user);
}
}
}
六、控制台
七、总结
通过Spring将Mybatis整合,工厂和sqlSession的创建不用在测试类中去新建,也不用专门写一个工具类获取sqlSession,我们只需要在spring-dao.xml中对工厂factory和sqlSessionTemplate进行配置,然后在多写一个实现类实现dao接口中的方法,我们在调用的时候直接调用方法,无需在获取sqlSession
整合方式二
一、编写实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
二、编写对应的接口
//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
//编写针对User表的相关操作,现在是查询用户
public List<User> selectUser(Map map);
}
三、编写Mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
<select id="selectUser" resultType="user" parameterType="map">
select * from mybatis.user
<where>
<if test="id !=null">
id = #{id}
</if>
</where>
</select>
</mapper>
四、配置spring-dao.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据源DataSource:使用Spring的数据源替换掉Mybatis中的配置,
我们现在使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
这里我们能导入是因为我们pom.xml中导入了spring-jdbc的依赖-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&characterEncoding=utf8&useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置sqlSessionFactory,将数据源通过set方法注入到sqlSessionFactory中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定Mybatis配置文件,name是写死的用configLocation,作用是将这个配置文件和mybatis-config.xml连接-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 配置注册Mapper.xml文件-->
<property name="mapperLocations" value="classpath:com/guohui/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们mybatis中使用的sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 将sqlSessionFactory使用有参构造器注入到SqlSessionTemplate中,因为SqlSessionTemplate类中没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
五、编写接口的实现类
/*
整合方式二:通过继承SqlSessionDaoSupport,为我们提供一个getSqlSession(),可以获取到SqlSessionTemplate
获取到之后,就可以直接调用getMapper方法,然后对数据库进行操作了
*/
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> selectUser(Map map) {
return getSqlSession().getMapper(UserMapper.class).selectUser(map);
}
}
六、将实现类在Spring中注册
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 导入Dao配置文件-->
<import resource="spring-dao.xml"/>
<!-- 注册UserMapperImpl.java实现类-->
<bean id="sqlSession" class="com.guohui.mapper.UserMapperImpl">
<!-- 将SqlSessionTemplate类型的sqlSession通过set方法注入到UserMapperImpl实现类中-->
<property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>
<!-- 注册注册UserMapperImpl2-->
<bean id="sqlSession2" class="com.guohui.mapper.UserMapperImpl2">
<!--由于我们继承的SqlSessionDaoSupport类中需要sqlSessionFactory,并且存在set方法,直接进行注入即可-->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
七、测试
public class MyTest {
@Test
public void test(){
//获取Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//我们现在只需要创建UserMapperImpl实现类的对象,调用里面的方法即可,注意,最后的类型要是接口的类型
UserMapper sqlSession = context.getBean("sqlSession2", UserMapper.class);
Map<Object, Object> map = new HashMap();
map.put("id",1);
for (User user : sqlSession.selectUser(map)) {
System.out.println(user);
}
}
}
八、控制台
至此,你已经深入的理解了Spring如何去整合Mybatis,并且对实现的原理也已经掌握,后续会继续更新,欢迎交流和指正!