创建Mybatis主配置文件:sqlMapConfig.xml;
创建Spring主配置文件:applicationContext.xml。
<configuration>
<typeAliases>
<package name="pers.goodwin.mybatis.bean" />
typeAliases>
configuration>
<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">
<context:property-placeholder location="jdbc.properties" />
<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>
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
bean>
beans>
#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
注意到在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"/>
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
bean>
在mybatis+spring整合中,可以在dao实现类中继承SqlSessionDaoSupport
,在SqlSessionDaoSupport
中可以通过getSqlSession()
方法获得session
。
SqlSession sqlSession = getSqlSession();
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");
}
}
<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">
<context:property-placeholder location="jdbc.properties" />
<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>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
bean>
<bean id="userDaoImpl" class="pers.goodwin.mybatis.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean">property>
bean>
beans>
<configuration>
<typeAliases>
<package name="pers.goodwin.mybatis.bean" />
typeAliases>
<mappers>
<mapper resource="pers/goodwin/mybatis/mapper/UserMapper.xml"/>
mappers>
configuration>
<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>
#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
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 + "]";
}
}
package pers.goodwin.mybatis.dao;
import pers.goodwin.mybatis.bean.User;
public interface UserDao {
public User getUserById(Integer id);
}
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]
在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;
}
}
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
<property name="mapperInterface" value="pers.goodwin.mybatis.mapper.UserMapper"/>
bean>
<configuration>
<typeAliases>
<package name="pers.goodwin.mybatis.bean" />
typeAliases>
<mappers>
<package name="pers.goodwin.mybatis.mapper"/>
mappers>
configuration>
<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>
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]
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="pers.goodwin.mybatis.mapper"/>
bean>