mybatis泛型DAO接口

本文将记录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>


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值