万能BaseMapper,BaseService,BaseController模板(偷懒专用)

1.目录结构(后期利用工具也能实现,建议前期自己编写,储存用作模板)
万能BaseMapper,BaseService,BaseController模板(偷懒专用)_第1张图片
2.创建BaseMapper接口

package com.liu.base;

import org.apache.ibatis.annotations.Param;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author root
 * @create 2020-12-21 15:28
 * 封装一些mapper 的简单方法
 */
public interface BaseMapper {
    //=================基础的增删改查操作========================
    /**
     * 插入一个实体类
     * @param entity
     * @return
     */
    int insert(T entity);

    /**
     * 根据实体类的主键删除一个实体
     * @param id
     */
    void deleteById(Serializable id);

    /**
     * 通过实体类删除
     * @param entity
     */
    void deleteByEntity(T entity);

    /**
     * 通过map删除
     * @param map
     */
    void deleteByMap(Map map);

    /**
     * 更新一个实体类
     * @param entity
     */
    void update(T entity);

    /**
     * 通过实体类的id来修改
     * @param entity
     */
    void updateById(T entity);

    /**
     * 根据参数查询
     * @param map
     * @return
     */
    List getListByMap(Map map);

    /**
     * 查询所有
     * @return
     */
    List getAll();

    /**
     * 查询所有的实体,根据实体的属性值,属性值作为条件
     * @param entity
     * @return
     */
    List getAllByEntity(T entity);

    /**
     * 根据主键获取一个实体
     * @param id
     * @return
     */
    T load(Serializable id);
    /**
     * 根据主键获取一个实体
     * @param id
     * @return
     */
    T getById(Serializable id);
    /**
     * 通过map查询----不分页
     * @param params
     * @return
     */
    T getByMap(Map params);

    /**
     * 通过对象查询----不分页
     * @param entity
     * @return
     */
    T getByEntity(T entity);

    //=========================分页查询中的操作=====================================
    //find*方法为分页查询的方法

    /**
     * 通过map进行分页查询
     * @param map
     * @return
     */
    public List findByMap(Map map);

    /**
     * 通过对象查询分页
     * @param entity
     * @return
     */
    public List findByEntity(T entity);

    /**
     * 需要自己写count 的分页
     * @param map
     * @return
     */
    public List findByCount(Map map);

    /**
     * 批量新增
     * @param list
     */
    public void insertBatch(List list);

    /**
     * 批量修改
     * @param list
     */
    public void updateBatch(List list);

    //=============================封装纯sql语句==================================

    /**
     * 通过sql 查询一个对象返回map集合
     * @param sql
     * @return
     */
    public Map getBySqlReturnMap(@Param("sql") String sql);

    /**
     * 通过sql查询一个对象返回实体类
     * @param sql
     * @return
     */
    public T getBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 通过sql查询到的map集合封装成List集合返回
     * @param sql
     * @return
     */
    public List> listBySqlReturnMap(@Param("sql") String sql);

    /**
     * 通过sql查询到的结果封装为List集合
     * @param sql
     * @return
     */
    public List listBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 查询分页
     * @param sql
     * @return
     */
    public List findBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 通过sql查询到的结果修改
     * @param sql
     */
    public void updateBysql(@Param("sql") String sql);

    /**
     * 通过sql删除
     * @param sql
     */
    public void deleteBySql(@Param("sql") String sql);
}

2.编写BaseService

package com.liu.base;

import com.liu.utils.Pager;
import org.apache.ibatis.annotations.Param;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author root
 * @create 2020-12-21 17:41
 */
public interface BaseService {
    //=================基础的增删改查操作========================
    /**
     * 插入一个实体类
     * @param entity
     * @return
     */
    int insert(T entity);

    /**
     * 根据实体类的主键删除一个实体
     * @param id
     */
    void deleteById(Serializable id);

    /**
     * 通过实体类删除
     * @param entity
     */
    void deleteByEntity(T entity);

    /**
     * 通过map删除
     * @param map
     */
    void deleteByMap(Map map);

    /**
     * 更新一个实体类
     * @param entity
     */
    void update(T entity);

    /**
     * 通过实体类的id来修改
     * @param entity
     */
    void updateById(T entity);

    /**
     * 根据参数查询
     * @param map
     * @return
     */
    public List getListByMap(Map map);

    /**
     * 查询所有
     * @return
     */
    List getAll();

    /**
     * 查询所有的实体,根据实体的属性值,属性值作为条件
     * @param entity
     * @return
     */
    List getAllByEntity(T entity);

    /**
     * 根据主键获取一个实体
     * @param id
     * @return
     */
    T load(Serializable id);
    /**
     * 根据主键获取一个实体
     * @param id
     * @return
     */
    T getById(Serializable id);
    /**
     * 通过map查询----不分页
     * @param params
     * @return
     */
    T getByMap(Map params);

    /**
     * 通过对象查询----不分页
     * @param entity
     * @return
     */
    T getByEntity(T entity);

    //=========================分页查询中的操作=====================================
    //find*方法为分页查询的方法

    /**
     * 通过map进行分页查询
     * @param map
     * @return
     */
    public Pager findByMap(Map map);

    /**
     * 通过对象查询分页
     * @param entity
     * @return
     */
    public Pager findByEntity(T entity);

    /**
     * 需要自己写count 的分页
     * @param map
     * @return
     */
    public List findByCount(Map map);

    /**
     * 批量新增
     * @param list
     */
    public void insertBatch(List list);

    /**
     * 批量修改
     * @param list
     */
    public void updateBatch(List list);

    //=============================封装纯sql语句==================================

    /**
     * 通过sql 查询一个对象返回map集合
     * @param sql
     * @return
     */
    public Map getBySqlReturnMap(@Param("sql") String sql);

    /**
     * 通过sql查询一个对象返回实体类
     * @param sql
     * @return
     */
    public T getBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 通过sql查询到的map集合封装成List集合返回
     * @param sql
     * @return
     */
    public List> listBySqlReturnMap(@Param("sql") String sql);

    /**
     * 通过sql查询到的结果封装为List集合
     * @param sql
     * @return
     */
    public List listBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 查询分页
     * @param sql
     * @return
     */
    public Pager findBySqlReturnEntity(@Param("sql") String sql);

    /**
     * 通过sql查询到的结果修改
     * @param sql
     */
    public void updateBysql(@Param("sql") String sql);

    /**
     * 通过sql删除
     * @param sql
     */
    public void deleteBySql(@Param("sql") String sql);
}

3.编写BaseServiceImpl

package com.liu.base;

import com.github.pagehelper.PageHelper;
import com.liu.utils.Pager;
import com.liu.utils.SystemContext;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author root
 * @create 2020-12-21 17:43
 * 抽象类  ----通过子类来完成实例化
 */
public abstract class BaseServiceImpl implements BaseService{

    public abstract BaseMapper getBaseMapper();

    public int insert(T entity) {
        return this.getBaseMapper().insert(entity);
    }

    public void deleteById(Serializable id) {
            this.getBaseMapper().deleteById(id);
    }

    public void deleteByEntity(T entity) {
           this.getBaseMapper().deleteByEntity(entity);
    }

    public void deleteByMap(Map map) {
           this.getBaseMapper().deleteByMap(map);
    }

    public void update(T entity) {
          this.getBaseMapper().update(entity);
    }

    public void updateById(T entity) {
         this.getBaseMapper().updateById(entity);
    }

    public List getListByMap(Map map) {
        return this.getBaseMapper().getListByMap(map);
    }

    public List getAll() {
        return this.getBaseMapper().getAll();
    }

    public List getAllByEntity(T entity) {
        return this.getBaseMapper().getAllByEntity(entity);
    }

    public T load(Serializable id) {
        return this.getBaseMapper().load(id);
    }

    public T getById(Serializable id) {
        return this.getBaseMapper().getById(id);
    }

    public T getByMap(Map params) {
        return this.getBaseMapper().getByMap(params);
    }

    public T getByEntity(T entity) {
        return this.getBaseMapper().getByEntity(entity);
    }

    public Pager findByMap(Map map) {
        /**
         * 执行分页
         */
        Integer pageSize = SystemContext.getPageSize();
        Integer pageOffset = SystemContext.getPageOffset();
        if(pageOffset==null||pageOffset<0) pageOffset = 0;
        if(pageSize==null||pageSize<0) pageSize = 15;
        String order = SystemContext.getOrder();
        String sort = SystemContext.getSort();
        Integer pageNum = null;
        if(pageOffset == 0){
            pageNum = 1;
        }else{
            pageNum = pageOffset/pageSize+1;
        }
        PageHelper.startPage(pageNum, pageSize);
        Pager pages = new Pager(this.getBaseMapper().findByMap(map));
        return pages;
    }

    public Pager findByEntity(T entity) {
        /**
         * 执行分页
         */
        Integer pageSize = SystemContext.getPageSize();
        Integer pageOffset = SystemContext.getPageOffset();
        if(pageOffset==null||pageOffset<0) pageOffset = 0;
        if(pageSize==null||pageSize<0) pageSize = 15;
        String order = SystemContext.getOrder();
        String sort = SystemContext.getSort();
        Integer pageNum = null;
        if(pageOffset == 0){
            pageNum = 1;
        }else{
            pageNum = pageOffset/pageSize+1;
        }
        PageHelper.startPage(pageNum, pageSize);
        Pager pages = new Pager(this.getBaseMapper().findByEntity(entity));
        return pages;
    }

    public List findByCount(Map map) {
        return this.getBaseMapper().findByCount(map);
    }

    public void insertBatch(List list) {
         this.getBaseMapper().insertBatch(list);
    }

    public void updateBatch(List list) {
         this.getBaseMapper().updateBatch(list);
    }

    public Map getBySqlReturnMap(String sql) {
        return this.getBaseMapper().getBySqlReturnMap(sql);
    }

    public T getBySqlReturnEntity(String sql) {
        return this.getBaseMapper().getBySqlReturnEntity(sql);
    }

    public List> listBySqlReturnMap(String sql) {
        return this.getBaseMapper().listBySqlReturnMap(sql);
    }

    public List listBySqlReturnEntity(String sql) {
        return this.getBaseMapper().listBySqlReturnEntity(sql);
    }

    public Pager findBySqlReturnEntity(String sql) {
        /**
         * 执行分页
         */
        Integer pageSize = SystemContext.getPageSize();
        Integer pageOffset = SystemContext.getPageOffset();
        if(pageOffset==null||pageOffset<0) pageOffset = 0;
        if(pageSize==null||pageSize<0) pageSize = 15;
        String order = SystemContext.getOrder();
        String sort = SystemContext.getSort();
        Integer pageNum = null;
        if(pageOffset == 0){
            pageNum = 1;
        }else{
            pageNum = pageOffset/pageSize+1;
        }
        PageHelper.startPage(pageNum, pageSize);
        Pager pages = new Pager(this.getBaseMapper().findBySqlReturnEntity(sql));
        return pages;
    }

    public void updateBysql(String sql) {
          this.getBaseMapper().updateBysql(sql);
    }

    public void deleteBySql(String sql) {
          this.getBaseMapper().deleteBySql(sql);
    }
    //判断空
    public boolean isEmpty(String str) {
        return (null == str) || (str.trim().length() <= 0);
    }

    public boolean isEmpty(Character cha) {
        return (null == cha) || cha.equals(' ');
    }

    public boolean isEmpty(Object obj) {
        return (null == obj);
    }

    public boolean isEmpty(Object[] objs) {
        return (null == objs) || (objs.length <= 0);
    }

    public boolean isEmpty(Collection obj) {
        return (null == obj) || obj.isEmpty();
    }

    public boolean isEmpty(Set set) {
        return (null == set) || set.isEmpty();
    }

    public boolean isEmpty(Serializable obj) {
        return null == obj;
    }

    public boolean isEmpty(Map map) {
        return (null == map) || map.isEmpty();
    }
}

4.编写BaseController

package com.liu.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author root
 * @create 2020-12-23 12:36
 */
public class BaseController {

    protected final static String DATE_FORMATE = "yyyy-MM-dd";

    // 下面是判断null的操作

    public boolean isEmpty(String str) {
        return (null == str) || (str.trim().length() <= 0);
    }

    public boolean isEmpty(Character cha) {
        return (null == cha) || cha.equals(' ');
    }

    public boolean isEmpty(Object obj) {
        return (null == obj);
    }

    public boolean isEmpty(Object[] objs) {
        return (null == objs) || (objs.length <= 0);
    }

    public boolean isEmpty(Collection obj) {
        return (null == obj) || obj.isEmpty();
    }

    public boolean isEmpty(Set set) {
        return (null == set) || set.isEmpty();
    }

    public boolean isEmpty(Serializable obj) {
        return null == obj;
    }

    public boolean isEmpty(Map map) {
        return (null == map) || map.isEmpty();
    }

    /**
     *
     * 获得map
     * @return
     */
    public Map getMap(){
        return new HashMap();
    }
}

5.编写****Mapper.xml



<mapper namespace="com.liu.mapper.SuperUserMapper">
         
    <resultMap id="ResultMapSuperUser" type="com.liu.pojo.SuperUser">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="realname" column="realname" jdbcType="VARCHAR"/>
    resultMap>

    <sql id="superuser_field">
        id,username,password,realname
    sql>

    <sql id="SuperUser_insert">
        #{id},#{username},#{password},#{realname}
    sql>

    <sql id="SuperUser_where">
        <if test="id!=null">
             id=#{id}
        if>
        <if test="username!=null">
            and username=#{username}
        if>
        <if test="password!=null">
            and password=#{password}
        if>
        <if test="realname!=null">
            and realname=#{realname}
        if>
    sql>
    
    <sql id="SuperUser_update">
        <if test="username!=null">
             username=#{username},
        if>
        <if test="password!=null">
             password=#{password},
        if>
        <if test="realname!=null">
             realname=#{realname}
        if>
    sql>

    <insert id="insert" parameterType="SuperUser" useGeneratedKeys="true" keyProperty="id">
           insert into pmxt.superuser(<include refid="superuser_field">include>)
           values (<include refid="SuperUser_insert">include>)
    insert>

    <delete id="deleteById" parameterType="Integer">
            delete from pmxt.superuser where id=#{id}
    delete>

    <delete id="deleteByEntity" parameterType="SuperUser">
        delete from pmxt.superuser where 1=1
       <include refid="SuperUser_where">include>
    delete>

    <delete id="deleteByMap" parameterType="java.util.HashMap">
        delete from pmxt.superuser where 1=1
        <include refid="SuperUser_where">include>
    delete>

    <update id="update" parameterType="SuperUser">
        update pmxt.superuser
        <set>
            <include refid="SuperUser_update">include>
        set>
        where 1=1
        <include refid="SuperUser_where">include>
    update>

    <update id="updateById" parameterType="SuperUser">
        update pmxt.superuser
        <set>
            <include refid="SuperUser_update">include>
        set>
        where id = #{id}
    update>

    <select id="getListByMap" resultMap="ResultMapSuperUser" parameterType="java.util.HashMap">
         select <include refid="superuser_field">include>
         from pmxt.superuser
         where 1=1
         <include refid="SuperUser_where">include>
    select>

    <select id="getAll" resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
    select>

    <select id="getAllByEntity" parameterType="SuperUser" resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
        where 1=1
        <include refid="SuperUser_where">include>
    select>
    
    <select id="load" parameterType="Integer" resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
        where id=#{id}
    select>

    <select id="getById" parameterType="Integer" resultMap="ResultMapSuperUser">
         select <include refid="superuser_field">include>
         from pmxt.superuser
         where id=#{id}
    select>

    <select id="getByMap" parameterType="java.util.HashMap" resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
        where 1=1
        <include refid="SuperUser_where">include>
    select>

    <select id="getByEntity" parameterType="SuperUser"  resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
        where 1=1
        <include refid="SuperUser_where">include>
    select>

<select id="findByMap" parameterType="java.util.HashMap" resultMap="ResultMapSuperUser">
    select <include refid="superuser_field">include>
    from pmxt.superuser
    where 1=1
    <include refid="SuperUser_where">include>
select>

    <select id="findByEntity" parameterType="SuperUser" resultMap="ResultMapSuperUser">
        select <include refid="superuser_field">include>
        from pmxt.superuser
        where 1=1
        <include refid="SuperUser_where">include>
    select>

    <insert id="insertBatch" parameterType="java.util.List">
        insert into pmxt.superuser(<include refid="superuser_field">include>)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.username},#{item.password},#{item.realname})
        foreach>
    insert>

    <update id="updateBatch" parameterType="java.util.List">
        <foreach collection="list" item="item" index="index" separator=";">
            update pmxt.superuser
            <set>
                <if test="item.username!=null">
                    username=#{item.username},
                if>
                <if test="item.password!=null">
                    password=#{item.password},
                if>
                <if test="item.realname!=null">
                    realname=#{item.realname}
                if>
            set>
            where 1=1
            <if test="item.id!=null">
                and id=#{item.id}
            if>
        foreach>
    update>


    <select id="getBySqlReturnMap" resultType="java.util.HashMap">
        ${sql}
    select>

    <select id="getBySqlReturnEntity" resultMap="ResultMapSuperUser">
        ${sql}
    select>

    <select id="listBySqlReturnMap" resultType="java.util.HashMap">
        ${sql}
    select>

    <select id="listBySqlReturnEntity" resultMap="ResultMapSuperUser">
        ${sql}
    select>

    <select id="findBySqlReturnEntity" resultMap="ResultMapSuperUser">
        ${sql}
    select>

    <update id="updateBysql">
        ${sql}
    update>

    <delete id="deleteBySql">
         ${sql}
    delete>
mapper>

6.修改部分代码,可以做到通用(以及批量处理那里修改以下)

<mapper namespace="com.liu.mapper.SuperUserMapper">
         
    <resultMap id="ResultMapSuperUser" type="com.liu.pojo.SuperUser">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="realname" column="realname" jdbcType="VARCHAR"/>
    resultMap>

    <sql id="superuser_field">
        id,username,password,realname
    sql>

    <sql id="SuperUser_insert">
        #{id},#{username},#{password},#{realname}
    sql>

    <sql id="SuperUser_where">
        <if test="id!=null">
             id=#{id}
        if>
        <if test="username!=null">
            and username=#{username}
        if>
        <if test="password!=null">
            and password=#{password}
        if>
        <if test="realname!=null">
            and realname=#{realname}
        if>
    sql>
    
    <sql id="SuperUser_update">
        <if test="username!=null">
             username=#{username},
        if>
        <if test="password!=null">
             password=#{password},
        if>
        <if test="realname!=null">
             realname=#{realname}
        if>
    sql>

7.正是开始三层架构
7.1编写dao层

package com.liu.mapper;

import com.liu.base.BaseMapper;
import com.liu.pojo.SuperUser;

/**
 * @author root
 * @create 2020-12-21 16:08
 */
public interface SuperUserMapper extends BaseMapper<SuperUser> {
}

7.2编写Service层

package com.liu.service;

import com.liu.base.BaseService;
import com.liu.pojo.SuperUser;

/**
 * @author root
 * @create 2020-12-21 17:42
 */
public interface SuperUserService extends BaseService<SuperUser>{
}
package com.liu.service.impl;

import com.liu.base.BaseMapper;
import com.liu.base.BaseServiceImpl;
import com.liu.mapper.SuperUserMapper;
import com.liu.pojo.SuperUser;
import com.liu.service.SuperUserService;
import com.liu.utils.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author root
 * @create 2020-12-21 17:43
 */
@Service
public class SuperUserServiceImpl extends BaseServiceImpl<SuperUser> implements SuperUserService{
    @Autowired
    SuperUserMapper superUserMapper;
    public BaseMapper<SuperUser> getBaseMapper() {
        return superUserMapper;
    }

}

7.3Controller层

package com.liu.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liu.base.BaseController;
import com.liu.pojo.User;
import com.liu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author root
 * @create 2020-12-22 19:14
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {
   @Autowired
   private UserService userService;

   /**
    * 查询所有用户,根据条件查询用户
    * @return
    */
   @GetMapping("/getUsers")
   public String getUsers(String tj,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum, Model model){
      String sql = "select * from user where 1=1 ";
      //拼接sql  条件拼接
      if(!isEmpty(tj)){
         sql += " and (username like '%"+tj+"%' or phone like '%"+tj+"%' or email like '%"+tj+"%')";
      }
      sql += " order by id";
      List<User> userList = userService.listBySqlReturnEntity(sql);
      PageHelper.startPage(pageNum,8);
      PageInfo<User> pageInfo = new PageInfo<User>(userList);
      model.addAttribute("pageInfo",pageInfo);
      return "admin/user_list";
   }

   /**
    * 删除用户
    * @return
    */
   @GetMapping("/delete/{id}")
   public String deleteUserById(@PathVariable("id") Integer id){
      userService.deleteById(id);
      return "redirect:/admin/user/getUsers";
   }

   /**
    * 去添加页面
    * @return
    */
   @RequestMapping("/toAdd")
   public String toAdd(Model model){
      User user = new User();
      model.addAttribute("user",user);
      return "admin/user_add";
   }
   @PostMapping("/add")
   public String addUser(@Valid User user){
      int i = userService.insert(user);
      return "redirect:/admin/user/getUsers";
   }

   /**
    * 去修改页面
    * @return
    */
   @RequestMapping("/toUpdate/{id}")
   public String toUpdate(Model model,@PathVariable("id") Integer id){
      User user = userService.getById(id);
      model.addAttribute("user",user);
      return "admin/user_update";
   }
   @PostMapping("/update")
   public String updateUser(@Valid User user){
        userService.updateById(user);
        return "redirect:/admin/user/getUsers";
   }
}

你可能感兴趣的:(直接Copy,mybatis,mysql)