本文将记录mybatis整合spring的泛型DAO接口,通过BasicDAOImpl实现类提供CRUD功能,其他DAO只需要继承和扩展BasicDAOImpl。
BasicDao接口定义
public interface BasicDAO<T extends BasicModel> {
T find(Long id);
T update(T bean);
Long insert(T bean);
int delete(Long id);
}
BasicDAOImpl实现类
public class BasicDAOImpl<T extends BasicModel> implements BasicDAO<T> {
protected Logger log = LoggerFactory.getLogger(getClass());
/**
* 预定义的Statement
*/
protected static final String INSERT = "insert";
protected static final String UPDATE = "update";
protected static final String DELETE_BY_ID = "deleteById";
protected static final String GET_BY_ID = "getById";
protected static final String DOT = ".";
protected Class<T> entityClass = null;
@SuppressWarnings("unchecked")
public BasicDAOImpl() {
//获取参数化类型
entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
protected String getStatementPrefix() {
return entityClass.getSimpleName() + DOT;
}
protected SqlSession getSession() {
return SqlSessionHolder.getSession();
}
public T find(Long id) {
@SuppressWarnings("unchecked")
List<T> list = getSession().selectList(getStatementPrefix()+GET_BY_ID, id);
if(list.isEmpty()){
throw new QueryException("查询数据失败");
}else{
return list.get(0);
}
}
public T update(BasicModel bean) {
int records = getSession().update(getStatementPrefix()+UPDATE, bean);
if (records == 0 || records == -1) {
throw new OptLockException("This record modified by another thread before commit,please try again");
}
return find(bean.getId());
}
public Long insert(BasicModel bean) {
getSession().insert(getStatementPrefix()+INSERT, bean);
return bean.getId();
}
public int delete(Long id) {
return getSession().delete(getStatementPrefix()+DELETE_BY_ID, id);
}
}
数据库session工具
public class SqlSessionHolder {
private static final Log logger = LogFactory.getLog(SqlSessionHolder.class);
private static ThreadLocal<SqlSession> sessionHolder = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlMapper = SqlMapClientHolder.getInstance().getSqlMapper();
public static void clearSession() {
if (sessionHolder.get() == null) {
return;
}
sessionHolder.get().close();
sessionHolder.set(null);
logger.debug("session close");
}
public static SqlSession getSession() {
if (sessionHolder.get() == null) {
logger.debug("initial session");
sessionHolder.set(sqlMapper.openSession(ExecutorType.REUSE, false));
}
return sessionHolder.get();
}
public static SqlSession getSession(ExecutorType executorType) {
if (sessionHolder.get() == null) {
sessionHolder.set(sqlMapper.openSession(executorType, false));
return sessionHolder.get();
}
return sessionHolder.get();
}
public static void setSession(SqlSession sqlSession) {
sessionHolder.set(sqlSession);
}
public static void commitSession() {
if (sessionHolder.get() == null) {
return;
}
sessionHolder.get().commit(true);
sessionHolder.get().close();
sessionHolder.set(null);
logger.debug("session close");
}
public static void rollbackSession() {
if (sessionHolder.get() == null) {
return;
}
sessionHolder.get().rollback(true);
sessionHolder.get().close();
sessionHolder.set(null);
logger.debug("session close");
}
}
mapper绑定
public class SqlMapClientHolder {
private static SqlSessionFactory sqlMapper;
private static final Log logger = LogFactory.getLog(SqlMapClientHolder.class);
private static SqlMapClientHolder sqlMapClientHolder = new SqlMapClientHolder();
private static String environmentId = "Test";
private SqlMapClientHolder() {
if (sqlMapper == null) {
try {
String ibatisResource = "ibatis-config.xml";
Reader ibatisReader = Resources.getResourceAsReader(ibatisResource);
sqlMapper = new SqlSessionFactoryBuilder().build(ibatisReader,environmentId);
logger.info("SqlSessionFactory built successfully.");
} catch (Exception e) {
e.printStackTrace();
logger.error(LogMessageUtil.printStack(e));
throw new RuntimeException(e);
}
}
}
public static SqlMapClientHolder getInstance() {
return sqlMapClientHolder;
}
public SqlSessionFactory getSqlMapper() {
return sqlMapper;
}
public void setSqlMapper(SqlSessionFactory sqlMapper) {
this.sqlMapper = sqlMapper;
}
public static void setEnvironmentId(String environmentId) {
SqlMapClientHolder.environmentId = environmentId;
}
}
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="uservo">
<insert id="insert" parameterType="uservo">
<selectKey keyProperty="id" resultType="long" order="BEFORE">
select user_sequence.nextval from dual
</selectKey>
INSERT INTO USER(
<!-- 0 --> id,
<!-- 1 --> name,
<!-- 2 --> age
)
VALUES(
<!-- 0 --> #{ id:NUMERIC },
<!-- 1 --> #{ name:VARCHAR },
<!-- 2 --> #{ age:NUMERIC }
)
</insert>
<update id="update" parameterType="uservo">
UPDATE USER SET
application = #{ name:VARCHAR },
service = #{ age:NUMERIC }
WHERE ID = #{id}
</update>
<delete id="deleteById" parameterType="long">
DELETE FROM USER WHERE ID = #{id}
</delete>
<select id="getById" parameterType="long" resultType="uservo">
SELECT * FROM USER WHERE ID = #{id}
</select>
</mapper>