基于spring注解,泛型的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuisongliu/article/details/49357659

/**
 * Service基类,所有Service均继承该类
 *
 */
public abstract class BaseService<T> {

    /* 所有子类直接通过该SQLSession操作数据库 */
    @Resource(name = "sqlSession")
    protected SqlSession sqlSession;

    protected Class<T> clazz;

    protected  String DOMAIN_NAME;

    /* 用于记录日志 */
    protected Logger logger=null ;

    @SuppressWarnings("unchecked")
    @PostConstruct
    public void postConstruct(){ 
        try {
            Type type= this.getClass().getGenericSuperclass();
            ParameterizedType parameterizedType=(ParameterizedType) type;
            clazz= (Class<T>) parameterizedType.getActualTypeArguments()[0];
            DOMAIN_NAME =clazz.getName();
        } catch (Exception e) {
            e.printStackTrace();
            clazz=null;
        }
        logger = LoggerFactory.getLogger(this.getClass());
    }



    // base根据主键ID查询方法
    @Transactional(readOnly = true)
    public T getByID(Long id)throws Exception {
        try {
            return sqlSession.selectOne(DOMAIN_NAME + ".selectByPrimaryKey", id);
        } catch (Exception e) {
            logger.error("根据{}获取{}发生错误:{}", id, DOMAIN_NAME,e.getMessage(), e);

            throw e;
        }
    }

    // base新增方法
    @Transactional
    public void saveBase(T entity) throws Exception{
        try {
            sqlSession.insert(DOMAIN_NAME+".insertSelective",entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    // base修改方法
    @Transactional
    public int updateBase(T entity) throws Exception{
        try{
            return sqlSession.update(DOMAIN_NAME+".updateByPrimaryKeySelective",entity);
        }catch(Exception e){
            logger.error(DOMAIN_NAME+"修改时发生错误:{}", e.getMessage(), e);
            throw e;
        }
    }

    // base删除方法
    @Transactional
    public void deleteBase(Long id) throws Exception {
        try {
            sqlSession.delete(DOMAIN_NAME + ".deleteByPrimaryKey", id);
        } catch (Exception e) {
            logger.error(DOMAIN_NAME+"删除时发生错误:{}", e.getMessage(), e);

            throw e;
        }
    }
}
阅读更多

没有更多推荐了,返回首页