Mybatis通用封装

本文针对Spring+SpringMVC+Mybatis基础框架。
在进行开发的时候,没有必要对每个增删改查进行实现,写接口写sql太麻烦了,严重影响开发效率,所以这里对其进行了通用基本方法的封装。

1、spring-application


<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:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.1.xsd  
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task-4.1.xsd     
    http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
    default-lazy-init="false">

    <task:annotation-driven />
    <tx:annotation-driven />
    <context:component-scan base-package="com.*.service" />

    
    
    
    <bean id="configProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:jdbc.propertiesvalue>
            list>
        property>
    bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
    bean>

    
    <bean id="dataSourceProxool" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
          
        <property name="initialSize" value="${database.initialSize}" />
         
        <property name="maxActive" value="${database.maxActive}" />
        
        <property name="minIdle" value="${database.minIdle}" />
         
        <property name="maxWait" value="${database.maxWait}" />
        
        <property name="validationQuery" value="${database.validationQuery}" />
         
        <property name="testOnBorrow" value="${database.testOnBorrow}" />
         
        <property name="testOnReturn" value="${database.testOnReturn}" />
        
        <property name="testWhileIdle" value="${database.testWhileIdle}" />
        
        <property name="timeBetweenEvictionRunsMillis" value="${database.timeBetweenEvictionRunsMillis}" />
         
        <property name="filters" value="${database.filters}" />
        
        <property name="proxyFilters">
            <list>
                <ref bean="stat-filter" />
            list>
        property>
    bean>

    <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
        
        <property name="slowSqlMillis" value="3000" />
        
        <property name="logSlowSql" value="true" />
        
        <property name="mergeSql" value="true" />
    bean>


    <bean id="druid-stat-interceptor"
        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
        scope="prototype">
        <property name="patterns">
            <list>
                <value>com.*.service.*value>
                <value>com.*.mapper.*value>
            list>
        property>
    bean>

    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor"
            pointcut-ref="druid-stat-pointcut" />
    aop:config>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSourceProxool" />
        <property name="mapperLocations">
            <array>
                <value>classpath:mapper/*.xmlvalue>
            array>
        property>
        <property name="typeAliasesPackage" value="com.*.entity" />
        <property name="plugins">
            <array>
            
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=oracle
                            returnPageInfo=check
                        value>
                    property>
                bean>
            array>
        property>
    bean>


    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.collection.mapper" />
        <property name="properties">
            <value>
                mappers=tk.mybatis.mapper.common.Mapper
            value>
        property>
    bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
        scope="prototype">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    bean>


    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     
          <property name="dataSource" ref="dataSourceProxool">property>
    bean>     
    
     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

beans>

2、BaseService


import java.util.List;

import com.github.pagehelper.PageInfo;

public interface BaseService
{

    public String save(T entity);

    public String delete(Object key);

    public String update(T entity);

    public String batchDelete(Object ids[]);

    public T findByPrimaryKey(Object key);

    /**
     * 查询单个对象:如果多条记录则会抛出异常
     * 
     * @param entity
     * @return
     */
    public T findByObject(T entity);

    public List queryExampleForList(Object example);

    public List queryObjectForList(String order);

    public List queryObjectForList();

    /**
     * 带条件查询所有
     * 
     * @param entity
     * @return
     */
    public List queryObjectForList(T entity);

    public PageInfo queryPageForList();

    public PageInfo queryPageForList(T entity);

}

3、BaseServiceImpl


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.collection.util.CommonUtil;

import tk.mybatis.mapper.common.Mapper;

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
@Service
public abstract class BaseServiceImpl implements BaseService
{

    protected static final String SUCCESS = "success";
    protected static final String ERROR = "error";
    protected Logger logger = Logger.getLogger(BaseServiceImpl.class);

    @Autowired
    protected Mapper mapper;

    public String save(T entity)
    {
        int result = 0;
        try
        {
            result = this.mapper.insertSelective(entity);
        } catch (Exception e)
        {
            logger.error("---add error---", e);
        }
        return result > 0 ? SUCCESS : ERROR;
    }

    public String delete(Object key)
    {
        int result = 0;
        try
        {
            result = this.mapper.deleteByPrimaryKey(key);
        } catch (Exception e)
        {
            logger.error("---del error---", e);
        }
        return result > 0 ? SUCCESS : ERROR;
    }

    public String update(T entity)
    {
        int result = 0;
        try
        {
            result = this.mapper.updateByPrimaryKeySelective(entity);
        } catch (Exception e)
        {
            logger.error("---add error---", e);
        }
        return result > 0 ? SUCCESS : ERROR;
    }

    public String batchDelete(Object ids[])
    {
        try
        {
            for (int i = 0; i < ids.length; i++)
            {
                delete(ids[i]);
            }
        } catch (Exception e)
        {
            logger.error("---batch error---", e);
            return ERROR;
        }
        return SUCCESS;
    }

    public T findByPrimaryKey(Object key)
    {
        try
        {
            return this.mapper.selectByPrimaryKey(key);
        } catch (Exception e)
        {
            logger.error("---find error---", e);
        }
        return null;
    }

    /**
     * 查询单个对象:如果多条记录则会抛出异常
     * 
     * @param entity
     * @return
     */
    public T findByObject(T entity)
    {
        try
        {
            return this.mapper.selectOne(entity);
        } catch (Exception e)
        {
            logger.error("错误的查询,检查是否返回多个结果集!", e);
        }
        return null;
    }

    public List queryExampleForList(Object example)
    {
        return this.mapper.selectByExample(example);
    }

    public List queryObjectForList(String order)
    {
        PageHelper.orderBy(order);
        return this.mapper.selectAll();
    }

    public List queryObjectForList()
    {
        return this.mapper.selectAll();
    }

    /**
     * 带条件查询所有
     * 
     * @param entity
     * @return
     */
    public List queryObjectForList(T entity)
    {
        return this.mapper.select(entity);
    }

    public PageInfo queryPageForList()
    {
        return queryPageForList(null);
    }

    public PageInfo queryPageForList(T entity)
    {
        HttpServletRequest request = CommonUtil.getHttpRequest();
        Integer pageNum = CommonUtil.valueOf(request.getParameter("pageNum"), 1);
        Integer pageSize = CommonUtil.valueOf(request.getParameter("pageSize"), 10);
        PageHelper.startPage(pageNum, pageSize);
        String orderField = request.getParameter("sort");
        String orderDirection = request.getParameter("order");
        if (StringUtil.isNotEmpty(orderField))
        {
            PageHelper.orderBy(orderField);
            if (StringUtil.isNotEmpty(orderDirection))
            {
                PageHelper.orderBy(orderField + " " + orderDirection);
            }
        }
        return new PageInfo(mapper.select(entity));
    }

}

4、以后的Mapper只要继承基本的mapper

import com.collection.entity.UserEntity;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<UserEntity>
{

}

5、service继承BaseService

import com.github.pagehelper.PageInfo;
import com.collection.entity.UserEntity;
import com.collection.service.BaseService;

public interface UserService extends BaseService<UserEntity>
{
}

6、serviceImpl继承BaseServiceImpl

@Service
public class UserServiceImpl extends BaseServiceImpl<UserEntity>implements UserService
{
    public PageInfo queryButtomForList()
    {
        return this.queryPageForList();
    }
}

你可能感兴趣的:(Mybatis)