引官网一段话:
SqlSessionDaoSupport 是 一 个 抽象 的支 持 类, 用来 为你 提供 SqlSession 。 调 用 getSqlSession()方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法
SqlSessionDaoSupport 需要一个 sqlSessionFactory 或 sqlSessionTemplate 属性来 设 置 。 这 些 被 明 确 地 设 置 或 由 Spring 来 自 动 装 配 。 如 果 两 者 都 被 设 置 了 , 那 么 SqlSessionFactory 是被忽略的。
本次环境如下(基于Maven 中推荐版本):
spring:4.2.5.RELEASE
mybatis:3.4.0
mybatis-spring:1.3.0
junit:4.12
表user_1,user_2,user_3 结构相同
以user_1为例:
CREATE TABLE `user_1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_id` int(11) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`update_id` int(11) DEFAULT NULL,
`deleted` bit(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
实体基类,封装公共属性:
public class BaseEntity {
protected Integer id;
protected Date createTime;
protected Integer createId;
protected Date updateTime;
protected Integer updateId;
protected Boolean deleted;
//省略setter getter
}
userA实体继承实体基类:
public class UserA extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
//省略setter getter
}
userB,userC类似
Mapper接口基类:
public interface BaseMapper {
int deleteByPrimaryKey(Integer id);
int insert(T record);
T selectByPrimaryKey(Integer id);
List selectAll();
int updateByPrimaryKey(T record);
}
抽象Mapper类:
public abstract class AbstractBaseMapper<T extends BaseEntity> extends SqlSessionDaoSupport implements BaseMapper<T> {
private static final String SQL_INSERT = "insert";
private static final String SQL_DELETE_BY_PRIMARY_KEY = "deleteByPrimaryKey";
private static final String SQL_UPDATE_BY_PRIMARY_KEY = "updateByPrimaryKey";
private static final String SQL_SELECT_BY_PRIMARY_KEY = "selectByPrimaryKey";
private static final String SQL_SELECT_ALL = "selectAll";
@Override
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
@Override
@Autowired
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
super.setSqlSessionTemplate(sqlSessionTemplate);
}
public String getStatement(String sqlId) {
//决定了mapper.xml namespace中的值
String name = this.getClass().getName();
StringBuilder sb = new StringBuilder();
sb.append(name).append(".").append(sqlId);
return sb.toString();
}
@Override
public int deleteByPrimaryKey(Integer id) {
return getSqlSession().delete(getStatement(SQL_DELETE_BY_PRIMARY_KEY), id);
}
@Override
public int insert(T record) {
return getSqlSession().insert(getStatement(SQL_INSERT), record);
}
@Override
public T selectByPrimaryKey(Integer id) {
return getSqlSession().selectOne(getStatement(SQL_SELECT_BY_PRIMARY_KEY), id);
}
@Override
public List selectAll() {
return getSqlSession().selectList(getStatement(SQL_SELECT_ALL));
}
@Override
public int updateByPrimaryKey(T record) {
return getSqlSession().update(getStatement(SQL_UPDATE_BY_PRIMARY_KEY), record);
}
}
说明:
SqlSessionDaoSupport 需要一个 sqlSessionFactory 或 sqlSessionTemplate 属性来 设 置
所以需做如下配置:
@Override
@Autowired
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
或
@Override
@Autowired
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
super.setSqlSessionTemplate(sqlSessionTemplate);
}
两个一起设置,sqlSessionFactory将被忽略
getStatement()方法用于定位具体需要执行的SQL,具体原理可参考MyBatis configuration.xml文件解析相关知识,也正是因为该方法,mapper.xml namespace的值和常规整合时的值不一样,常规整合时是Mapper接口的全限定类名,而此处将会是Mapper接口具体实现类的全限定类名
public String getStatement(String sqlId) {
//决定了mapper.xml namespace中的值
String name = this.getClass().getName();
StringBuilder sb = new StringBuilder();
sb.append(name).append(".").append(sqlId);
return sb.toString();
}
此时UaerADao只需要继承BaseMapper,UserADaoImpl 继承AbstractBaseMapper并实现UserADao接口即可,AbstractBaseMapper中实现了常见所需方法
public interface UserADao extends BaseMapper<UserA>{
}
public class UserADaoImpl extends AbstractBaseMapper<UserA> implements UserADao {
}
UserADao对应的Mapper.xml文件内容如下(此时该文件是什么名称并不重要):
version="1.0" encoding="UTF-8" ?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
"com.example.dao.impl.UserADaoImpl">
id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user_1
where id = #{id,jdbcType=INTEGER}
id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="UserA">
insert into user_1 (name, create_time,
create_id, update_time, update_id,
deleted)
values (#{name,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP},
#{createId,jdbcType=INTEGER}, #{updateTime,jdbcType=TIMESTAMP}, #{updateId,jdbcType=INTEGER},
#{deleted,jdbcType=BIT})
id="updateByPrimaryKey" parameterType="UserA">
update user_1
set name = #{name,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=TIMESTAMP},
create_id = #{createId,jdbcType=INTEGER},
update_time = #{updateTime,jdbcType=TIMESTAMP},
update_id = #{updateId,jdbcType=INTEGER},
deleted = #{deleted,jdbcType=BIT}
where id = #{id,jdbcType=INTEGER}
该配置文件直接利用驼峰命名转换实现数据库列与实体属性的映射
spring配置文件如下:
<context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="typeAliasesPackage" value="com.example.entity">property>
<property name="mapperLocations" value="classpath:mybatis/**/*.xml">property>
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<property name="mapUnderscoreToCamelCase" value="true" />
bean>
property>
bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
bean>
若UserADao接口 需要定义自己单独的方法,如:
public interface UserADao extends BaseMapper<UserA>{
UserA selectByName(String name);
}
实现类如下做即可:
public class UserADaoImpl extends AbstractBaseMapper<UserA> implements UserADao {
@Override
public UserA selectByName(String name) {
return getSqlSession().selectOne("selectByName", name);
}
}
注意上述selectOne(“selectByName”, name)中的selectByName即映射文件中的sql id:
该方式与利用代码生成器直接生成的方式各有利弊,看官自己选择