属性值为空不更新到数据库工具类

最近项目用的hibernate,有通用得数据库操作类,但是由于tk得mybatis的工具类用习惯了,它有只更新不为null值的方法,但是为空串依然会更新,下面有设置空串为null的工具以及注解类

/**
 * @(#) BaseDao.java Created on 2010-5-17
 * 
 * Copyright (c) 2010 Aspire. All Rights Reserved
 */
package com.diandi.web.dao.impl;

import java.lang.reflect.Field;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.diandi.annotation.Update;
import com.diandi.web.dao.IBaseDao;

/**
 * The class <code>BaseDao</code>
 * 
 * @author hejie
 * @version 1.0
 */
@Repository("baseDao")
public class BaseDao implements IBaseDao {
   

    /**
     * <p>Title: updateByPrimaryKeySelective</p>  
     * <p>Description: 字段值有则更新无则忽略  不支持对象嵌套
     * @param entity  
     * @author hejie*/
    @Override
    public void updateByPrimaryKeySelective(Object entity) {
        try {
            Class<? extends Object> clazz = entity.getClass();
            Table table = clazz.getAnnotation(Table.class);
            // 表名
            String tableName = table.name();
            StringBuilder sql = new StringBuilder("update " + tableName + " set ");
            StringBuilder param = new StringBuilder();
            // 获取所有私有属性
            Field[] dfields = clazz.getDeclaredFields();
            // 获取有id注解的值
            Object primaryKey = null;
            // 获取主键的字段名
            String primaryKeyColumnName = null;
            for (Field f : dfields) {
                // 私有属性访问权限
                f.setAccessible(true);
                // 判断是否存在id注解,不能更新主键
                Id id = f.getAnnotation(Id.class);
                // 主键得操作
                if(id != null){
                    primaryKey = f.get(entity);
                    if(primaryKey == null){
                        throw new RuntimeException("主键为空,更新失败!");
                    }
                    Column column = f.getAnnotation(Column.class);
                    primaryKeyColumnName = column.name();
                }
                // 非主键字段的操作
                if(id == null){
                    Column column = f.getAnnotation(Column.class);
                    JoinColumn joinColumn = f.getAnnotation(JoinColumn.class);
                    if(column != null || joinColumn != null){
                        // 数据库字段名
                        String dbColumn = column != null ? column.name() : joinColumn.name();
                        Object object = null;
                        // 获取对象得主键
                        if(joinColumn != null && f.get(entity) != null){
                            object = getPrimaryKey(f.get(entity));
                        }else{
                            object = f.get(entity);
                        }
                        
                        // 先判断是否存在注解
                        Update update = f.getAnnotation(Update.class);
                        if(update != null){
                            // 是否为true
                            boolean isNull = update.isNullUpdate();
                            if(isNull){
                                // 字段值
                                if(object != null){
                                    param.append(dbColumn + " = '" + object + "', ");
                                }else{
                                    param.append(dbColumn + " = " + null + ", ");
                                }
                                continue;
                            }
                        }
                        // 字段值
                        if(object != null){
                            param.append(dbColumn + " = '" + object + "', ");
                        }
                    }
                }
            }
            // 再次判断主键名和值是否完整
            if(primaryKey == null || StringUtils.isBlank(primaryKeyColumnName)){
                throw new RuntimeException("主键为空,更新失败!");
            }
            String updateSql = sql.append(param.substring(0,param.lastIndexOf(","))).toString() + " where " + primaryKeyColumnName + " = " + primaryKey;
            // entityMgr.createNativeQuery(updateSql).executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 获取属性为对象得主键
    public String getPrimaryKey(Object object){
        try {
            Class<? extends Object> clazz = object.getClass();
            Field[] dFields = clazz.getDeclaredFields();
            for (Field f : dFields) {
                f.setAccessible(true);
                // 判断是否存在id注解,不能更新主键
                Id id = f.getAnnotation(Id.class);
                // 主键得操作
                if(id != null){
                    System.out.println(f.get(object));
                    return f.get(object) + "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

设置属性值为空串的为null,或者直接在上面工具判断一下就好

package com.diandi.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: CodeUtil  
 * @Description: 编码转换
 * @author 何杰  
 * @date 2020年5月27日  
 *
 */
public class ObjUtil {

    
    // 对象编码处理
    public static <T> T toUtf8(T t) {
        Class<? extends Object> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Class<?> type = field.getType();
                if(type.isAssignableFrom(String.class)){
                    String value = (String)field.get(t);
                    if(value != null){
                        field.set(t, new String(value.getBytes("ISO8859-1"),"UTF-8"));
                    }
                }
                field.get((Object)t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return t;
    }
    
    
    // 对象转map
    public static Map<String, String> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, String> map = new HashMap<String,String>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if(!fieldName.equals("serialVersionUID")){
                String value = field.get(obj) + "";
                map.put(fieldName, value);
            }
        }
        return map;
    }
    
    /**
     * 设置空串为null
     */
    public static <T> T changeToNull(T o) {
        Class c = o.getClass();
        Class sc = c.getSuperclass();
        if (null != sc) {
            recursionNull(sc, o);
        }
        try {
            Field[] fs = c.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String st = f.get(o) + "";
                String str = st.replaceAll(" ", "");
                if (str.equals("") || str == null || str.equals("null")) {
                    f.set(o, null);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * 判断是否有超类,若有则继续将超类的空值置空
     * 
     * @param sc
     * @param o
     * @return
     */
    public static <T> T recursionNull(Class sc, T o) {
        Class c = sc.getSuperclass();
        if (null != c) {
            recursionNull(c, o);
        }
        try {

            Field[] fs = sc.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String st = f.get(o) + "";
                String str = st.replaceAll(" ", "");
                if (str.equals("") || str == null || str.equals("null")) {
                    f.set(o, null);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }
    
}

 注解类:为什么要有这个呢,有些时候值为null也需要更新,在字段上加上该注解并设置值为null会对null值得属性进行拼接(本该设置默认值为true的,添加注解不用谢括号里的值就行,需要用的话可以改改)

package com.diandi.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD}) 
@Retention(RetentionPolicy.RUNTIME)
public @interface Update {

    /**
     * 为true时即使为null值也需要进行更新
     */
    boolean isNullUpdate() default false;
    
}

 

posted @ 2020-07-06 09:21  明年上初中  阅读(522)  评论(0编辑  收藏  举报