Mybatis学习笔记_8、Mybatis+Spring整合开发

1.目的

  • 使用Spring容器单例模式管理Mybatis的SqlSessionFactory;
  • 使用Spring管理连接池、数据源等;
  • 将Dao/Mapper动态代理对象注入到Spring容器中,使用时直接获取。

2.Mybatis和Spring整合:

  • 导入所需的包;
    在这里插入图片描述

    • Mybatis+Spring整合包:下载地址
    • Mybatis核心包
    • 连接数据库相关的包
    • Spring相关的包
  • 创建Mybatis主配置文件:sqlMapConfig.xml;

  • 创建Spring主配置文件:applicationContext.xml。

3.连接测试

配置sqlMapConfig.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>
	<typeAliases>
		<!-- <typeAlias alias="user" type="pers.goodwin.mybatis.bean.User"/> -->
		<!-- 推荐使用扫描包的形式来配置别名 包的形式会扫描包及子包下的所有文件, 以对象类名为别名,大小写不敏感,推荐使用小写 -->
		<package name="pers.goodwin.mybatis.bean" />
	</typeAliases>
</configuration>

配置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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 读取jdbc.properties -->
	<context:property-placeholder location="jdbc.properties" />
	
	<!-- 配置C3P0连接池************* -->
	<bean name="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>
	
	<!-- 配置Mybatis sqlSessionFactory -->
	<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置数据源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 告诉spring mybatis的核心配置文件 -->
		<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
	</bean>
</beans>

jdbc.properties

#database configuration information
jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db_shopsystem?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.user=root
jdbc.password=123456

jdbc.initPoolSize=5
jdbc.maxPoolSize=1000

测试

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
SqlSessionFactoryBean bean = ac.getBean(SqlSessionFactoryBean.class);
System.out.println(bean);

输出

org.mybatis.spring.SqlSessionFactoryBean@51fadaff

4.Dao式开发

注意到在mybatis常规的dao开发中,每次都要通过SqlSessionFactory创建sqlSession

// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");

//sqlSessionFactoryBuilder
SqlSessionFactoryBuilder ssb = new SqlSessionFactoryBuilder();

//创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = ssb.build(inputStream);

// 通过SqlSessionFactory创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();

在spring中,可以将sqlSessionFactory交给spring管理

<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 配置数据源 -->
	<property name="dataSource" ref="dataSource"/>
	<!-- 告诉spring mybatis的核心配置文件 -->
	<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>

在mybatis+spring整合中,可以在dao实现类中继承SqlSessionDaoSupport,在SqlSessionDaoSupport中可以通过getSqlSession()方法获得session

SqlSession sqlSession = getSqlSession();

SqlSessionDaoSupport.java :
在这里插入图片描述

public abstract class SqlSessionDaoSupport extends DaoSupport {
  private SqlSessionTemplate sqlSessionTemplate;
  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (this.sqlSessionTemplate == null || sqlSessionFactory != this.sqlSessionTemplate.getSqlSessionFactory()) {
      this.sqlSessionTemplate = createSqlSessionTemplate(sqlSessionFactory);
    }
  }
  @SuppressWarnings("WeakerAccess")
  protected SqlSessionTemplate createSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
  public final SqlSessionFactory getSqlSessionFactory() {
    return (this.sqlSessionTemplate != null ? this.sqlSessionTemplate.getSqlSessionFactory() : null);
  }
  public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
    this.sqlSessionTemplate = sqlSessionTemplate;
  }
  public SqlSession getSqlSession() {
    return this.sqlSessionTemplate;
  }
  public SqlSessionTemplate getSqlSessionTemplate() {
    return this.sqlSessionTemplate;
  }
  @Override
  protected void checkDaoConfig() {
    notNull(this.sqlSessionTemplate, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
  }
}

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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 读取jdbc.properties -->
	<context:property-placeholder location="jdbc.properties" />
	
	<!-- 配置C3P0连接池************* -->
	<bean name="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
	</bean>
	
	<!-- 配置Mybatis sqlSessionFactory -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置数据源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 告诉spring mybatis的核心配置文件 -->
		<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
	</bean>
	
	<!-- userDao -->
	<bean id="userDaoImpl" class="pers.goodwin.mybatis.dao.UserDaoImpl">
		<!-- 将工厂注入到dao的父类sqlSessionFactory -->
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
	</bean>
</beans>

sqlMapConfig.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>
	<typeAliases>
		<!-- <typeAlias alias="user" type="pers.goodwin.mybatis.bean.User"/> -->
		<!-- 推荐使用扫描包的形式来配置别名 包的形式会扫描包及子包下的所有文件, 以对象类名为别名,大小写不敏感,推荐使用小写 -->
		<package name="pers.goodwin.mybatis.bean" />
	</typeAliases>
	<mappers>
		<mapper resource="pers/goodwin/mybatis/mapper/UserMapper.xml"/>
	</mappers>
</configuration>

UserMapper.xml

<mapper namespace="UserMapper">
	<resultMap id="userResultMap" type="User">
		 <id property="id" column="u_id" />
		 <result property="username" column="u_username"/>
		 <result property="password" column="u_password"/>
		 <result property="gender" column="u_gender"/>
		 <result property="cid" column="u_cid"/>
	</resultMap>

	<select id="selectUserById" parameterType="Integer" resultMap="userResultMap">
		select * from t_user where u_id = #{id}
	</select>
</mapper>

jdbc.properties

#database configuration information
jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db_ssm_mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.user=root
jdbc.password=123456

User.java

package pers.goodwin.mybatis.bean;

/**
 * @author goodwin
 *
 */
public class User {
	private Integer  id;
	private String  username;
	private String  password;
	private Integer  gender;
	private Integer  cid;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Integer getCid() {
		return cid;
	}
	public void setCid(Integer cid) {
		this.cid = cid;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", gender=" + gender + ", cid="
				+ cid + "]";
	}
}

UserDao.java

package pers.goodwin.mybatis.dao;

import pers.goodwin.mybatis.bean.User;

public interface UserDao {
	public User getUserById(Integer id);
}

UserDaoImpl.java

package pers.goodwin.mybatis.dao;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import pers.goodwin.mybatis.bean.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
	@Override
	public User getUserById(Integer id) {
		SqlSession sqlSession = getSqlSession();
		//参数1:要操作的SQL语句,参数2:SQL的参数
		return sqlSession.selectOne("UserMapper.selectUserById", id);
	}
}

测试代码

package pers.goodwin.mybatis.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pers.goodwin.mybatis.bean.User;
import pers.goodwin.mybatis.dao.UserDaoImpl;

public class UserDaoTest {
	@Test
	public void DaoTest() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDaoImpl userDao = ac.getBean(UserDaoImpl.class);
		User user = userDao.getUserById(1);
		System.out.println(user);
	}
}

测试结果

JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@502f1f4c [wrapping: com.mysql.cj.jdbc.ConnectionImpl@6f8f9349]] will not be managed by Spring
==>  Preparing: select * from t_user where u_id = ?
==> Parameters: 1(Integer)
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3e10dc6]
User [id=1, username=隔壁老王, password=6666666, gender=0, cid=1]

5.mapper动态代理开发

在Dao式开发中,可以通过spring获得sqlSessionFactory,然后通过SqlSession sqlSession = getSqlSession();获得sqlSession进而进行操作。
mybatis-spring核心包的MapperFactoryBean.class中,继承了Dao式开发中所说的SqlSessionDaoSupport。因此可以在MapperFactoryBean.class中获得sqlSession

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {

  private Class<T> mapperInterface;

  private boolean addToConfig = true;

  public MapperFactoryBean() {
    // intentionally empty
  }

  public MapperFactoryBean(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
  @Override
  protected void checkDaoConfig() {
    super.checkDaoConfig();

    notNull(this.mapperInterface, "Property 'mapperInterface' is required");

    Configuration configuration = getSqlSession().getConfiguration();
    if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
      try {
        configuration.addMapper(this.mapperInterface);
      } catch (Exception e) {
        logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
        throw new IllegalArgumentException(e);
      } finally {
        ErrorContext.instance().reset();
      }
    }
  }
  @Override
  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }
  @Override
  public Class<T> getObjectType() {
    return this.mapperInterface;
  }
  @Override
  public boolean isSingleton() {
    return true;
  }
  public void setMapperInterface(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
  public Class<T> getMapperInterface() {
    return mapperInterface;
  }
  public void setAddToConfig(boolean addToConfig) {
    this.addToConfig = addToConfig;
  }
  public boolean isAddToConfig() {
    return addToConfig;
  }
}

applicationContext.xml

<!-- mapper动态代理开发 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<!-- 注入sqlSessionFactory -->
	<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	<!-- 配置接口 -->
	<property name="mapperInterface" value="pers.goodwin.mybatis.mapper.UserMapper"/>
</bean>

sqlMapConfig.xml

<configuration>
	<typeAliases>
		<package name="pers.goodwin.mybatis.bean" />
	</typeAliases>
	<mappers>
		<package name="pers.goodwin.mybatis.mapper"/>
	</mappers>
</configuration>

UserMapper.xml

<mapper namespace="pers.goodwin.mybatis.mapper.UserMapper">
	<resultMap id="userResultMap" type="User">
		 <id property="id" column="u_id" />
		 <result property="username" column="u_username"/>
		 <result property="password" column="u_password"/>
		 <result property="gender" column="u_gender"/>
		 <result property="cid" column="u_cid"/>
	</resultMap>
	<select id="selectUserById" parameterType="Integer" resultMap="userResultMap">
		select * from t_user where u_id = #{id}
	</select>
</mapper>

UserMapper.java

	public User selectUserById(Integer id);

测试代码

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = ac.getBean(UserMapper.class);
User user = userMapper.selectUserById(1);
System.out.println(user);

测试结果

JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@502f1f4c [wrapping: com.mysql.cj.jdbc.ConnectionImpl@6f8f9349]] will not be managed by Spring
==>  Preparing: select * from t_user where u_id = ?
==> Parameters: 1(Integer)
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3e10dc6]
User [id=1, username=隔壁老王, password=6666666, gender=0, cid=1]

6.mapper动态扫描开发

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<property name="basePackage" value="pers.goodwin.mybatis.mapper"/>
</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值