博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MyBatis之通用化动态SQL
阅读量:3712 次
发布时间:2019-05-21

本文共 7950 字,大约阅读时间需要 26 分钟。

我们在上一篇整合SpringBoot的基础之上,再进行本篇的实验。

总体思路是将实体对象转成map后传给mybatis去执行,将mybatis的执行结果由map转成实体对象后输出。

首先CommDao.xml

insert into ${db.tableName}
${key}
values
#{val}
delete from ${db.tableName} where ${db.primaryKeyName}=#{params.${db.primaryKeyName}}
update ${db.tableName} set
${key}= #{params.${key}}
where ${db.primaryKeyName} =#{params.${db.primaryKeyName}}

CommDao

package com.yj.dao;import java.util.Map;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import com.yj.comm.model.DbProperties;@Repositorypublic interface CommDao {    void insert(@Param("params") Map
map, @Param("db") DbProperties dbProperties); void deleteByPrimaryKey(@Param("params") Map
map, @Param("db") DbProperties dbProperties); void updateByPrimaryKey(@Param("params") Map
map, @Param("db") DbProperties dbProperties); Map
selectByPrimaryKey(@Param("params") Map
map, @Param("db") DbProperties dbProperties);}

DbProperties

package com.yj.comm.model;import java.io.Serializable;/** * @param tableName 表名 * @param primaryKeyName 库表的主键名称 */public class DbProperties implements Serializable {	private static final long serialVersionUID = 2134017968462962008L;	private String tableName;	private String primaryKeyName;	public String getTableName() {		return tableName;	}	public void setTableName(String tableName) {		this.tableName = tableName;	}	public String getPrimaryKeyName() {		return primaryKeyName;	}	public void setPrimaryKeyName(String primaryKeyName) {		this.primaryKeyName = primaryKeyName;	}}

User

package com.yj.model;public class User{    private Integer id;    private String name;        private Integer age;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name == null ? null : name.trim();    }	public Integer getAge() {		return age;	}	public void setAge(Integer age) {		this.age = age;	}	@Override	public String toString() {		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";	}}

CommService

package com.yj.service;import java.io.IOException;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.yj.comm.model.DbProperties;import com.yj.comm.util.CommUtil;import com.yj.dao.CommDao;@Servicepublic class CommService {	@Autowired	private CommDao commDao;	public void insert(Object object, DbProperties dbProperties) {		Map
map = CommUtil.objectToMap(object); commDao.insert(map, dbProperties); } public void deleteByPrimaryKey(Object object, DbProperties dbProperties) { Map
map = CommUtil.objectToMap(object); commDao.deleteByPrimaryKey(map, dbProperties); } public void updateByPrimaryKey(Object object, DbProperties dbProperties) { Map
map = CommUtil.objectToMap(object); commDao.updateByPrimaryKey(map, dbProperties); } public Object selectByPrimaryKey(Object object, DbProperties dbProperties) throws IOException { Map
map = CommUtil.objectToMap(object); map=commDao.selectByPrimaryKey(map, dbProperties); return CommUtil.mapToObject(map, object.getClass()); }}

CommUtil

package com.yj.comm.util;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.Method;import java.sql.Timestamp;import java.text.SimpleDateFormat;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import com.alibaba.fastjson.JSON;public class CommUtil {    private static Pattern pattern = Pattern.compile("_(\\w)");    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    public static String camelToUnderline(String str) {        int len = str.length();        StringBuilder sb = new StringBuilder(len);        for (int i = 0; i < len; i++) {            char c = str.charAt(i);            if (Character.isUpperCase(c)) {                sb.append("_");                sb.append(Character.toLowerCase(c));            } else {                sb.append(c);            }        }        return sb.toString();    }    public static String underlineToCamel(String str) {        str = str.toLowerCase();        final StringBuffer sb = new StringBuffer();        Matcher m = pattern.matcher(str);        while (m.find()) {            m.appendReplacement(sb, m.group(1).toUpperCase());        }        m.appendTail(sb);        return sb.toString();    }	public static Map
objectToMap(Object bean) { Map
returnMap = null; try { Class type = bean.getClass(); returnMap = new HashMap
(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (result != null) { returnMap.put(CommUtil.camelToUnderline(propertyName), result); } else { returnMap.put(CommUtil.camelToUnderline(propertyName), ""); } } } } catch (Exception e) { e.printStackTrace(); } return returnMap; } public static
T mapToObject(Map
map, Class
clazz) { T result = null; Map
dataMap = new HashMap<>(); for (Map.Entry
entry : map.entrySet()) { String key = CommUtil.underlineToCamel(entry.getKey()); Object value = entry.getValue(); if (value instanceof Timestamp) { value = format.format(value); } dataMap.put(key, value); } String json = JSON.toJSONString(dataMap); result = JSON.parseObject(json, clazz); return result; }}

准备完毕,我们进行单元测试

CommServiceTest

package com.yj.service;import java.io.IOException;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import com.yj.ApplicationTest;import com.yj.comm.model.DbProperties;import com.yj.model.User;public class CommServiceTest extends ApplicationTest{	private Logger log = LoggerFactory.getLogger(this.getClass());		@Autowired	private CommService commService;		@Test	public void insert() {		User user =new User();		user.setName("test1");		user.setAge(18);		DbProperties dbProperties=new DbProperties();		dbProperties.setPrimaryKeyName("id");		dbProperties.setTableName("user");		commService.insert(user, dbProperties);	}		@Test	public void deleteByPrimaryKey() {		User user =new User();		user.setId(14);		DbProperties dbProperties=new DbProperties();		dbProperties.setPrimaryKeyName("id");		dbProperties.setTableName("user");		commService.deleteByPrimaryKey(user, dbProperties);	}		@Test	public void updateByPrimaryKey() {		User user =new User();		user.setId(13);		user.setName("aaa");		user.setAge(19);		DbProperties dbProperties=new DbProperties();		dbProperties.setPrimaryKeyName("id");		dbProperties.setTableName("user");		commService.updateByPrimaryKey(user, dbProperties);	}		@Test	public void selectByPrimaryKey() throws IOException {		User user =new User();		user.setId(13);		DbProperties dbProperties=new DbProperties();		dbProperties.setPrimaryKeyName("id");		dbProperties.setTableName("user");		User result=(User) commService.selectByPrimaryKey(user, dbProperties);		log.info("result:"+result);	}}

基于动态SQL的最基本增删改查的操作成功

转载地址:http://epsjn.baihongyu.com/

你可能感兴趣的文章
关于在VS2017中运行程序中颜色与源代码中颜色不符的问题
查看>>
Kali 2020.2虚拟机安装及安装后配置教程(图文小白版)
查看>>
C语言编程0基础学习历程(7)——C的函数
查看>>
洛谷——P2241 统计方形(数据加强版)(数学+暴力枚举)
查看>>
Windows Server 2008 安装教程——图文小白版(附下载地址)
查看>>
Windows Server 2003 安装教程——图文小白版(附下载地址)
查看>>
Jarvis OJ BASIC 公倍数
查看>>
sqli-lab 闯关教程 Less-1
查看>>
sqli-lab 闯关教程 Less-2
查看>>
sqli-lab 闯关教程 Less-3
查看>>
sqli-lab 闯关教程 Less-4
查看>>
sqli-lab 闯关教程 Less-5
查看>>
Ping 命令详解(含真实操作截图)
查看>>
L1-002 打印沙漏 (20分) C++版 AC代码
查看>>
L1-005 考试座位号 (15分) C++版 AC代码
查看>>
L1-049 天梯赛座位分配 (20分) AC代码
查看>>
L1-006 连续因子 (20分) C++版 AC代码
查看>>
C# 计算器窗体程序
查看>>
虚拟机安装winxp系统出现 non-bootable disk 80 的解决办法
查看>>
鼠标指针乱跑的解决方案
查看>>