博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
程序中设置MySQL的默认值
阅读量:6671 次
发布时间:2019-06-25

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

hot3.png

import com.alibaba.fastjson.JSON;import java.beans.PropertyDescriptor;import java.lang.annotation.*;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.math.BigDecimal;import java.text.ParseException;import java.text.SimpleDateFormat;import java.time.LocalDateTime;import java.time.ZoneOffset;import java.util.*;/** * mysql 参数 */public interface MysqlConstants {    /**     * 数据库中varchar类型为null时,用该值表示,程序中进行转换     * 字段='NONE' <=> 字段 is null     */    String NULL_VARCHAR = "NONE";    /**     * 数据库中datetime类型时为空,用该值表示,程序中进行转换     * 如果需要查找为空的为,只需要令 字段=NULL_DATE即可走索引,避免IS NULL ,IS NOT NULL的效率问题     * 该日期为 8888-12-31 23:59:59,距离现在还有6000多年,6000年以后的系统就让6000年以后的人去维护就行了     * 由于Date类型不是安全类型,有可能会被程序不小心改变值,所以程序中通过new Date(NULL_DATE_MILLS)来设置默认值,     * 从而避免NULL_DATE的值会被改变     */    long NULL_DATE_MILLS = LocalDateTime.of(8888, 12, 31, 23, 59, 59).toInstant(ZoneOffset.of("+8")).toEpochMilli();    /**     * 时间字符串最大值,避免将空值取出,比空值少一秒     */    String MAX_DATETIME_STR = "8888-12-31 23:59:58";    /**     * tinyint     */    Byte DEF_BYTE = 0;    /**     * short     */    Short DEF_SHORT = 0;    /**     * int     */    Integer DEF_INT = 0;    /**     * bigint     */    Long DEF_LONG = 0L;    /**     * float     */    Float DEF_FLOAT = 0F;    /**     * double     */    Double DEF_DOUBLE = 0D;    /**     * decimal     */    BigDecimal DEF_DECIMAL = BigDecimal.valueOf(0);    /**     * tinyint(1)     */    Boolean DEF_BOOLEAN = Boolean.FALSE;    /**     * mysql 默认值跟空值的转换     * 对应的field必须有可访问的setter getter 方法     */    @Target({ElementType.FIELD})    @Retention(RetentionPolicy.RUNTIME)    @Documented    @interface CastMysqlDefaultNullValue {        /**         * 默认使用MysqlConstants中的默认值         * @return         */        String defaultValue() default "";        /**         * 将默认值字符串转成特定的数据类型         * @return         */        Class
cast() default MysqlConstantsCast.MysqlConstantsDefaultCast.MysqlConstantsDefaultCast.class; } interface MysqlConstantsCast { /** * 将默认值转换为特别值 * @param defaultValue * @param target 目标类型 * @return */
T cast(String defaultValue, Class
target); class MysqlConstantsDefaultCast implements MysqlConstantsCast { @Override public
T cast(String defaultValue, Class
target) { if (target == String.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.NULL_VARCHAR : defaultValue); } if (target == Byte.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_BYTE : Byte.valueOf(defaultValue)); } if (target == Short.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_SHORT : Short.valueOf(defaultValue)); } if (target == Integer.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_INT : Integer.valueOf(defaultValue)); } if (target == Long.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_LONG : Long.valueOf(defaultValue)); } if (target == Float.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_FLOAT : Float.valueOf(defaultValue)); } if (target == Double.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_DOUBLE : Double.valueOf(defaultValue)); } if (target == BigDecimal.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_DECIMAL : BigDecimal.valueOf(Double.valueOf(defaultValue))); } if (target == Boolean.class) { return (T)(defaultValue.isEmpty() ? MysqlConstants.DEF_BOOLEAN : Boolean.valueOf(defaultValue)); } if (target == Date.class) { try { return (T)(defaultValue.isEmpty() ? new Date(MysqlConstants.NULL_DATE_MILLS) : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(defaultValue)); } catch (ParseException e) { throw new RuntimeException(e); } } throw new RuntimeException("无法将默认值[" + defaultValue + "]转换成" + target.getName() + "类型"); } } } /** * 目前只处理 String Date Integer 的默认值,其他的通过接口提供 */ class MysqlConstantsUtil { private static final Map
, Member[]> classMembers = new HashMap<>(); /** * 将目标方法中的空值换成默认值 */ public static void castNullToDefaultValue(Object dest) { try { Member[] members = getMembers(dest.getClass()); if (members != null && members.length > 0) { for (Member member : members) { if (member.getMethod.invoke(dest) == null) { member.setMethod.invoke(dest, new Object[]{member.defaultValue});//设置默认值 } } } } catch (Throwable e) { throw new RuntimeException(e); } } /** * 将默认值转成null,主要给前端展示用 * @param dest */ public static void castDefaultValueToNull(Object dest) { try { Member[] members = getMembers(dest.getClass()); if (members != null && members.length > 0) { for (Member member : members) { Object value = member.getMethod.invoke(dest); //等于默认值 if (value != null && value.equals(member.defaultValue)) { member.setMethod.invoke(dest, new Object[]{null}); } } } } catch (Throwable e) { throw new RuntimeException(e); } } private static Member[] getMembers(Class
target) { Member[] members = classMembers.get(target); if (members == null) { synchronized (target) { members = classMembers.get(target); if (members == null) { try { members = parseMembers(target); } catch (Exception e) { throw new RuntimeException(e); } classMembers.put(target, members); } } } return members; } private static Member[] parseMembers(Class
target) throws Exception { List
members = new ArrayList<>(); List
fieldList = new ArrayList<>(); Class
clazz = target; while (clazz != null && clazz != Object.class) { fieldList.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } for (Field field : fieldList) { field.setAccessible(true); CastMysqlDefaultNullValue castMysqlDefaultNullValue = field.getAnnotation(CastMysqlDefaultNullValue.class); if (castMysqlDefaultNullValue != null) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), target); Method getMethod = pd.getReadMethod(); Method setMethod = pd.getWriteMethod(); if (getMethod == null || setMethod == null) { throw new RuntimeException(target.getName() + "." + field.getName() + "没有相应的setter/getter方法"); } if (getMethod.getReturnType().isPrimitive()) { throw new RuntimeException("注解" + CastMysqlDefaultNullValue.class.getName() + "不支持基本类型"); } Object defaultValue = castMysqlDefaultNullValue.cast().newInstance().cast(castMysqlDefaultNullValue.defaultValue(), field.getType()); members.add(new Member(defaultValue, field, getMethod, setMethod)); } } return members.toArray(new Member[members.size()]); } //测试效果用的 static class CastTest { @CastMysqlDefaultNullValue Byte byte1; @CastMysqlDefaultNullValue Short short1; @CastMysqlDefaultNullValue Integer integer; @CastMysqlDefaultNullValue Long long1; @CastMysqlDefaultNullValue String string; @CastMysqlDefaultNullValue Float float1; @CastMysqlDefaultNullValue Double double1; @CastMysqlDefaultNullValue Date date; @CastMysqlDefaultNullValue BigDecimal bigDecimal; @CastMysqlDefaultNullValue Boolean boolean1; public Byte getByte1() { return byte1; } public void setByte1(Byte byte1) { this.byte1 = byte1; } public Short getShort1() { return short1; } public void setShort1(Short short1) { this.short1 = short1; } public Integer getInteger() { return integer; } public void setInteger(Integer integer) { this.integer = integer; } public Long getLong1() { return long1; } public void setLong1(Long long1) { this.long1 = long1; } public String getString() { return string; } public void setString(String string) { this.string = string; } public Float getFloat1() { return float1; } public void setFloat1(Float float1) { this.float1 = float1; } public Double getDouble1() { return double1; } public void setDouble1(Double double1) { this.double1 = double1; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getBigDecimal() { return bigDecimal; } public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } public Boolean getBoolean1() { return boolean1; } public void setBoolean1(Boolean boolean1) { this.boolean1 = boolean1; } } public static void main(String[] args) { CastTest castTest = new CastTest(); castNullToDefaultValue(castTest); System.out.println(JSON.toJSONString(castTest)); castDefaultValueToNull(castTest); System.out.println(JSON.toJSONString(castTest)); } } class Member { Object defaultValue; Field field; Method getMethod; Method setMethod; Member(Object defaultValue, Field field, Method getMethod, Method setMethod) { this.defaultValue = defaultValue; this.field = field; this.getMethod = getMethod; this.setMethod = setMethod; } }}

 

转载于:https://my.oschina.net/linchuhao23/blog/2989147

你可能感兴趣的文章
web图片优化(5)
查看>>
千里之行始于足下 | 开篇 - 增长极客
查看>>
[知识图谱] 1.2-知识图谱有什么用?
查看>>
EMOS搭建过程以及安装后配置
查看>>
LVS-NAT模式工作原理及配置
查看>>
我的友情链接
查看>>
Oracle IO问题解析(七)
查看>>
【HAVENT原创】k8s docker 管理 和 网页接口 监控系统
查看>>
1111111
查看>>
linux 学习前的准备 centos6的安装!
查看>>
Linux 下 IPsec-tools的使用
查看>>
ssh使用公钥授权不通过的问题解决
查看>>
iPad2 A5完美越狱获得重大进展--转载
查看>>
linux 调优 I/O 优化
查看>>
我的友情链接
查看>>
python内置函数2-callable()
查看>>
Python WindowsError
查看>>
nginx配置虚拟主机(2) - ttlsa教程系列之nginx
查看>>
postgresql安装
查看>>
零刻数据提供多地优质BGP双线接入服务
查看>>