基于通用Mapper封装的工具类

开发环境

  • 开发工具 idea
  • 开发使用的技术:
    spring +SpringMVC 或Spring boot + Mybatis+通用Mapper+获取音频大小的jave+mybatis+mysql
    页面:bootStrup+Gqurid

本文主要讲解工具类的封装

  • Util
    • CrudMapperImpl(基础的增删改)
      ExtensionMapperImpl(扩展的增删改)
      SecurityCode(验证码的封装)
      SecurityImage(验证码的封装)
      SelectAllPagingMapperImpl(分页 的查询)
  • 测试使用的
    • Service
    • Controller

pom.xml文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.6.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.baizhigroupId>
    <artifactId>cmfzartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>cmfzname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>

        

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

        

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>org.apache.tomcat.embedgroupId>
            <artifactId>tomcat-embed-jasperartifactId>
        dependency>

        
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.19version>
        dependency>


        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.46version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.54version>
        dependency>

        
        
        <dependency>
            <groupId>com.github.dadiyanggroupId>
            <artifactId>javeartifactId>
            <version>1.0.5version>
        dependency>

        
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-baseartifactId>
            <version>3.2.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-webartifactId>
            <version>3.2.0version>
        dependency>
        <dependency>
            <groupId>cn.afterturngroupId>
            <artifactId>easypoi-annotationartifactId>
            <version>3.2.0version>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>


    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

CrudMapper

package com.util.service;

import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.Map;

/**
 * 封装了crud 的Map集合的方法
 */
@Repository // spring dao层的注解
public interface CrudMapper<T> {
    Map<String, Object> add(T args, Mapper<T> mapper, String id);

    Map<String, Object> edit(T args, Mapper<T> mapper, String id);

    Map<String, Object> del(T args, Mapper<T> mapper, String id);
}

crudMapperImpl

package com.util;

import com.util.service.CrudMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;

import java.util.HashMap;
import java.util.Map;

@Service // spring 事物的注解
/**
 * 封装crud操作 为Map集合
 *       status 状态
 *       状态的信息
 * 当前实体类可以脱离接口单独使用
 * */
public class CrudMapperImpl<T> implements CrudMapper<T> {
    /**
     * 这是封装的添加方法
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     * @param id     当前对象的Id
     *               如果id是需要通过雪花算法或UUID生成的需要自己设置
     */
    @Override
    public Map<String, Object> add(T args, Mapper<T> mapper, String id) {
        Map<String, Object> map = new HashMap<>();
        try {
            mapper.insertSelective(args);
            map.put("status", true);
            map.put("message", id);
        } catch (Exception e) {
            map.put("status", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    /**
     * 这是封装的修改方法
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     * @param id     当前对象的Id
     *               如果id是需要通过雪花算法或UUID生成的需要自己设置
     *               status 可修改  message 可修改
     */
    @Override
    public Map<String, Object> edit(T args, Mapper<T> mapper, String id) {
        Map<String, Object> map = new HashMap<>();
        try {
            mapper.updateByPrimaryKeySelective(args);
            map.put("status", true);
            map.put("message", id);
        } catch (Exception e) {
            map.put("status", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    /**
     * 封装删除方法
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     * @param id     当前对象的Id
     *               如果id是需要通过雪花算法或UUID生成的需要自己设置
     *               status 可修改  message 可修改
     */
    @Override
    public Map<String, Object> del(T args, Mapper<T> mapper, String id) {
        Map<String, Object> map = new HashMap<>();
        try {
            mapper.deleteByPrimaryKey(args);
            map.put("status", true);
            map.put("message", id);
        } catch (Exception e) {
            map.put("status", false);
            map.put("message", e.getMessage());
        }
        return map;

    }
}

CrudExtenstionMapper

package com.util.service;

import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

import java.util.Map;

/**
 * 封装的添加方法(扩展)
 * 封装的修改方法(扩展)
 * 封装的删除方法(扩展)
 */
@Repository
public interface ExtensionMapper<T> {
    Map<String, Object> add(T args, Mapper<T> mapper);

    Map<String, Object> edit(T args, Mapper<T> mapper);

    Map<String, Object> del(T args, Mapper<T> mapper);
}

CrudExtensionMapperImpl

package com.util;

import com.baizhi.util.service.ExtensionMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;

import java.util.Map;

/**
 * @see
 */
@Service
public class ExtensionMapperImpl<T> implements ExtensionMapper<T> {
    /**
     * 封装的添加方法(扩展)
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     * @see 由于业务的不一样,我预留了扩展接口
     */

    @Override
    public Map<String, Object> add(T args, Mapper<T> mapper) {
        return null;
    }

    /**
     * 封装的修改方法(自己定义)
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     *               status 可修改  message 可修改
     * @see
     */

    @Override
    public Map<String, Object> edit(T args, Mapper<T> mapper) {
        return null;
    }

    /**
     * 封装删除方法(扩展)
     *
     * @param args   需要的对象
     * @param mapper 调用mapper的一些方法
     *               status 可修改  message 可修改
     * @see
     */

    @Override
    public Map<String, Object> del(T args, Mapper<T> mapper) {
        return null;
    }

}

SelectAllPagingMapper

package com.util.service;

import tk.mybatis.mapper.common.Mapper;

import java.util.Map;

public interface SelectAllPagingMapper<T> {
    Map<String, Object> selectAllPaging(Integer page, Integer rows, Mapper<T> mapper, T args);
}

SelectAllPagingMapperImpl

package com.baizhi.util;

import com.baizhi.util.service.SelectAllPagingMapper;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询所有的分页方法
 */
@Service
public class SelectAllPagingMapperImpl<T> implements SelectAllPagingMapper<T> {
    /**
     * 此方法是分页查询所有使用通用Mapper封装
     * Integer page, 页数
     * Integer rows, 当前页中的条数
     * Mapper mapper, 使用一个类继承mapper就可以使用Mapper的所有方法
     * Object args 所有对象的父类,查询当前页数需要的参数,查询当前对象在数据库有多少条需要的对象
     */
    @Override
    public Map<String, Object> selectAllPaging(Integer page, Integer rows, Mapper<T> mapper, T args) {
        Map<String, Object> map = new HashMap<>();
        RowBounds rowBounds = new RowBounds((page - 1) * rows, rows);
        List<T> banners = mapper.selectByRowBounds(args, rowBounds);
        int count = mapper.selectCount(args);
        map.put("page", page);       //当前页码数值
        map.put("rows", banners);    //当前页中的banner数据
        map.put("total", count % rows == 0 ? count / rows : count / rows + 1); //总页数
        map.put("records", count);   //总条数
        return map;
    }

}

UploadUtil

package com.baizhi.util.service;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service // 结合spring使用时需要注入 我使用@service注入
/**
 * 文件上传的工具类
 *
 * */
public class UploadUtil {
    /**
     * 文件上传的方法
     */
    public Map<String, Object> uploadFile(HttpSession httpSession, MultipartFile multipartFile, String realPath) throws IOException, EncoderException {
        Map<String, Object> map = new HashMap<>();
        if (realPath != null) {
            //获取文件的路径
            String getRealPath = httpSession.getServletContext().getRealPath(realPath);
            if (multipartFile.getOriginalFilename() != null) {
                //文件上传
                File file = new File(getRealPath, multipartFile.getOriginalFilename());
                multipartFile.transferTo(file);
                //获取文件的大小
                BigDecimal size = new BigDecimal(multipartFile.getSize());
                // 设置除数 转换成相同类型
                BigDecimal dom = new BigDecimal(1024);
                // 计算文件的大小 换算成MB
                BigDecimal bigDecimal = size.divide(dom).divide(dom).setScale(2, BigDecimal.ROUND_HALF_UP);
                map.put("bigDecimal", bigDecimal);
                map.put("OriginalFilename", multipartFile.getOriginalFilename());
                if (file != null) {
                    //获取文件时常
                    Encoder encoder = new Encoder();
                    long duration = encoder.getInfo(file).getDuration();
                    String Duration = duration / 1000 / 60 + ":" + duration / 1000 % 60;
                    map.put("Duration", Duration);
                }
            }

        }

        return map;
    }
}

测试 Controller

package com.controller;

import com.dao.ChapterDao;
import com.entity.Chapter;
import com.service.ChapterService;
import com.util.service.CrudMapper;
import com.util.service.SelectAllPagingMapper;
import com.util.service.UploadUtil;
import it.sauronsoftware.jave.EncoderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/chapter")
public class ChapterController {
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterDao chapterDao;

    @Qualifier("selectAllPagingMapperImpl")
    @Autowired
    private SelectAllPagingMapper<Chapter> selectAllPaging;
    @Qualifier("crudMapperImpl")
    @Autowired
    private CrudMapper<Chapter> crudMapper;
    @Autowired
    private UploadUtil uploadUtil;

    @RequestMapping("/selectChaptersBuAlbumId")
    @ResponseBody
    public Map<String, Object> getPage(Integer page, Integer rows, String albumId) {
        System.out.println("albumId = " + albumId);
        System.out.println("page = " + page);
        System.out.println("rows = " + rows);
        Chapter chapter = new Chapter();
        chapter.setAlbumId(albumId);
        Map<String, Object> stringObjectMap = selectAllPaging.selectAllPaging(page, rows, chapterDao, chapter);
        return stringObjectMap;
    }

    @RequestMapping("/edit")
    @ResponseBody
    public Map<String, Object> editBanner(String oper, Chapter chapter, String albumId) {
        System.out.println("albumId = " + albumId);
        System.out.println(oper);
        System.out.println("chapter = " + chapter);

        Map<String, Object> map = new HashMap<>();
        if (oper.equals("add")) {
            chapter.setId(UUID.randomUUID().toString());
            chapter.setCreateDate(new Date());
            chapter.setAlbumId(albumId);
            map = crudMapper.add(chapter, chapterDao, chapter.getId());
        }
        if (oper.equals("edit")) {
            chapter.setAlbumId(albumId);
            map = chapterService.edit(chapter, chapterDao);
        }
        if (oper.equals("del")) {
            map = crudMapper.del(chapter, chapterDao, chapter.getId());
        }
        return map;
    }

    @RequestMapping("/upload")
    @ResponseBody
    public void upload(String id, MultipartFile name, HttpSession httpSession) throws IOException, EncoderException {
        Chapter chapter = new Chapter();
        chapter.setId(id);
        Map<String, Object> map = uploadUtil.uploadFile(httpSession, name, "album/music");
        map.forEach((k, v) -> {
            if (k.equals("OriginalFilename")) {
                chapter.setName((String) v);
            }
            if (k.equals("Duration")) {
                chapter.setDuration((String) v);
            }
            if (k.equals("bigDecimal")) {
                chapter.setSize(v + "MB");
            }
            System.out.println("k = " + k);
            System.out.println("v = " + v);
        });

        chapterService.edit(chapter, chapterDao);
    }

}

ChapterService

package com.service;

import com.entity.Chapter;
import com.util.service.ExtensionMapper;
import tk.mybatis.mapper.common.Mapper;

import java.util.Map;
/**
这个crud工具的扩展类
*/
public interface ChapterService extends ExtensionMapper<Chapter> {

    @Override
    Map<String, Object> add(Chapter args, Mapper<Chapter> mapper);

    @Override
    Map<String, Object> edit(Chapter args, Mapper<Chapter> mapper);

    @Override
    Map<String, Object> del(Chapter args, Mapper<Chapter> mapper);
}

ChapterServiceImpl

package com.baizhi.service.serviceImpl;

import com.baizhi.entity.Chapter;
import com.baizhi.service.ChapterService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;

import java.util.HashMap;
import java.util.Map;

@Service
public class ChapterServiceImpl implements ChapterService {


    @Override
    public Map<String, Object> add(Chapter args, Mapper<Chapter> mapper) {
        return null;
    }
/**
需求: 我需要在修改图片时,如果我没有选择图片图片的默认值不会改变
*/
    @Override
    public Map<String, Object> edit(Chapter args, Mapper<Chapter> mapper) {
        Map<String, Object> map = new HashMap<>();
        try {
            if ("".equals(args.getName())) {
                args.setName(null);
            }
            // 如果 cover 的值是string就将其设置为null,防止修改
            mapper.updateByPrimaryKeySelective(args);
            map.put("status", true);
            map.put("message", args.getId());
        } catch (Exception e) {
            map.put("status", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @Override
    public Map<String, Object> del(Chapter args, Mapper<Chapter> mapper) {
        return null;
    }
}

SecurityCode

package com.baizhi.util;

import java.util.Arrays;

/**
 * 
 * @author others
 * date:2014-8-26  下午2:17:19
 * 描述:随机生成验证码值:验证码串
 */
public class SecurityCode {
	/**
	 * 验证码难度级别
	 *   Simple-数字
	 *   Medium-数字和小写字母 
	 *   Hard-数字和大小写字母
	 */
	public enum SecurityCodeLevel {
		Simple, Medium, Hard
	};
	/**
	 * 产生默认验证码,4位中等难度
	 *
	 * @return
	 */
	public static String getSecurityCode() {
		return getSecurityCode(4, SecurityCodeLevel.Medium, false);
	}
	/**
	 * 产生长度和难度任意的验证码
	 *
	 * @param length
	 * @param level
	 * @param isCanRepeat
	 * @return
	 */
	private static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
		// 随机抽取len个字符
		int len = length;
		// 字符集合(--除去易混淆的数字0,1,字母l,o,O)
		char[] codes = {
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
				'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
		};
		// 根据不同难度截取字符串
		if (level == SecurityCodeLevel.Simple) {
			codes = Arrays.copyOfRange(codes, 0, 10);
		} else if (level == SecurityCodeLevel.Medium) {
			codes = Arrays.copyOfRange(codes, 0, 36);
		}
		// 字符集和长度
		int n = codes.length;
		// 抛出运行时异常
		if (len > n && isCanRepeat == false) {
			throw new RuntimeException(String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常," + "当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s", len, level, isCanRepeat, n));
		}
		// 存放抽取出来的字符
		char[] result = new char[len];
		// 判断能否出现重复字符
		if (isCanRepeat) {
			for (int i = 0; i < result.length; i++) {
				// 索引0 and n-1
				int r = (int) (Math.random() * n);
				// 将result中的第i个元素设置为code[r]存放的数值
				result[i] = codes[r];
			}
		} else {
			for (int i = 0; i < result.length; i++) {
				// 索引0 and n-1
				int r = (int) (Math.random() * n);
				// 将result中的第i个元素设置为code[r]存放的数值
				result[i] = codes[r];
				// 必须确保不会再次抽取到那个字符,这里用数组中最后一个字符改写code[r],并将n-1
				codes[r] = codes[n - 1];
				n--;
			}
		}
		return String.valueOf(result);
	}
	public static void main(String[] args) {

		System.out.println(SecurityCode.getSecurityCode());
	}
}

SecurityImage

package com.baizhi.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

public class SecurityImage {
    /**
     * 生成验证码图片

     * @param securityCode

     * @return

     */
    public static BufferedImage createImage(String securityCode){

        int codeLength = securityCode.length();//验证码长度

        int fontSize = 15;//字体大小

        int fontWidth = fontSize+1;



        //图片宽高

        int width = codeLength*fontWidth+6;

        int height = fontSize*2+1;

        //图片

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //画板
        Graphics2D g = image.createGraphics();

        g.setColor(Color.WHITE);//设置背景色

        g.fillRect(0, 0, width, height);//填充背景

        g.setColor(Color.LIGHT_GRAY);//设置边框颜色

        g.setFont(new Font("Arial", Font.BOLD, height-2));//边框字体样式

        g.drawRect(0, 0, width-1, height-1);//绘制边框

        //绘制噪点

        Random rand = new Random();

        g.setColor(Color.LIGHT_GRAY);

        for (int i = 0; i < codeLength*6; i++) {

            int x = rand.nextInt(width);

            int y = rand.nextInt(height);

            g.drawRect(x, y, 1, 1);//绘制1*1大小的矩形

        }

        //绘制验证码

        int codeY = height-10;

        g.setColor(new Color(19,148,246));

        g.setFont(new Font("Georgia", Font.BOLD, fontSize));
        for(int i=0;i<codeLength;i++){
            double deg=new Random().nextDouble()*20;
            g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);
            g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);
            g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);
        }

        g.dispose();//关闭资源

        return image;

    }



}

感谢您的观看,我当前封装的工具类我觉得挺实用,如果您看到后觉得有什么不好,您在我的博客下边留言。勿喷!!!@本篇文章归本人所有,翻版必究!!!

你可能感兴趣的:())