Hibernate5.4工具类

原创
2020/05/07 10:16
阅读数 75

 SpIn.java

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

@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SpIn {
	int order();
}

SpOut.java

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

@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SpOut {
	int order();
}

 DBKit.java

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.ParameterMode;

import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.hibernate.procedure.ProcedureCall;
import org.hibernate.procedure.ProcedureOutputs;
import org.hibernate.query.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

@Repository("dbkit")
public class DBKit {
	
	@Resource
	protected SessionFactory sessionFactory;
	
	/**
	 * 原生查询绑定实体的列表
	 * 
	 * @param sql
	 * @param clazz
	 * @param args
	 * @return
	 * @throws Exception 
	 */
	public <T> List queryBean(String sql, Class<T> clazz, Object... args) throws Exception{
		Query query=sessionFactory.getCurrentSession().createSQLQuery(sql)
				.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		if(args!=null){
			for(int i=0, length=args.length; i<length; ++i){
				query.setParameter(i+1, args[i]);
			}
		}
		List list=query.list();
		Map<String, Object> map=null;
		T obj=null;
		int size=list.size();
		List<T> objs=new ArrayList<>(size);
		for(int i=0; i<size; ++i){
			map=(Map<String, Object>) list.get(i);
			obj=clazz.newInstance();
			reflex(clazz, obj, map);
			objs.add(obj);
		}
		
		return objs;
	}
	
	/**
	 * 原生查询Object列表
	 * 
	 * @param sql
	 * @param clazz
	 * @param args
	 * @return
	 * @throws Exception 
	 */
	public List queryObj(String sql, Object... args){
		Query query=sessionFactory.getCurrentSession().createSQLQuery(sql);
		if(args!=null){
			for(int i=0, length=args.length; i<length; ++i){
				query.setParameter(i+1, args[i]);
			}
		}
		
		return query.list();
	}
	
	/**
	 * 原生查询一个绑定实体
	 * 
	 * @param sql
	 * @param clazz
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public <T> T getBean(String sql, Class<T> clazz, Object... args) throws Exception{
		Query query=sessionFactory.getCurrentSession().createSQLQuery(sql)
				.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		if(args!=null){
			for(int i=0, length=args.length; i<length; ++i){
				query.setParameter(i+1, args[i]);
			}
		}
		List<Map<String, Object>> list=query.list();
		T obj=null;
		if(list.size()>0){
			Map<String, Object> map=list.get(0);
			obj=clazz.newInstance();
			reflex(clazz, obj, map);
		}
		
		return obj;
	}
	
	/**
	 * 原生查询一个Object
	 * 
	 * @param sql
	 * @param clazz
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public <T> T findObj(String sql, Class<T> clazz, Object... args){
		Query query=sessionFactory.getCurrentSession().createSQLQuery(sql);
		if(args!=null){
			for(int i=0, length=args.length; i<length; ++i){
				query.setParameter(i+1, args[i]);
			}
		}
		List<Object> list=query.list();
		Object obj=null;
		T val=null;
		if(list.size()>0){
			obj=list.get(0);
			if(Number.class.isAssignableFrom(clazz)){
				if(clazz==Integer.class){
					val=(T) Integer.valueOf(((BigDecimal)obj).intValue());
				}else if(clazz==Long.class){
					val=(T) Long.valueOf(((BigDecimal)obj).longValue());
				}else if(clazz==Double.class){
					val=(T) Double.valueOf(((BigDecimal)obj).doubleValue());
				}else{
					val=(T) obj;
				}
			}else if(clazz==String.class){
				val=(T) obj.toString();
			}else{
				val=(T) obj;
			}
		}
		
		return val;
	}
	
	/**
	 * 根据ID查询实体
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public <T> T getById(Class<T> clazz, Serializable id) throws Exception{
		return (T) sessionFactory.getCurrentSession().get(clazz, id);
	}
	
	/**
	 * 执行原生update/delete操作
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public int execSql(String sql, Object... args){
		Query query=sessionFactory.getCurrentSession().createSQLQuery(sql);
		if(args!=null){
			for(int i=0, length=args.length; i<length; ++i){
				query.setParameter(i+1, args[i]);
			}
		}
		
		return query.executeUpdate();
	}
	
	/**
	 * 保存实体数据
	 * 
	 * @param obj
	 */
	public void save(Object obj){
		sessionFactory.getCurrentSession().save(obj);
	} 
	
	/**
	 * 修改实体数据
	 * 
	 * @param obj
	 */
	public void update(Object obj){
		sessionFactory.getCurrentSession().update(obj);
	}
	
	/**
	 * 删除实体数据
	 * 
	 * @param obj
	 */
	public void delete(Object obj){
		sessionFactory.getCurrentSession().delete(obj);
	}
	
	/**
	 * 执行返回map的存储过程
	 * 
	 * @param name 存储过程名称
	 * @param dto 参数绑定的实体类
	 * @return
	 * @throws Exception
	 */
	public MapKit execProc(String name, Object dto) throws Exception{
		ProcedureCall proc=sessionFactory.getCurrentSession().createStoredProcedureCall(name);
		Class clazz=dto.getClass();
        Field[] fields=clazz.getDeclaredFields();
        Field field=null;
        for(int i=0, length=fields.length; i<length; ++i){
        	field=fields[i];
            if(field.isAnnotationPresent(SpIn.class)){//设置输入参数
            	SpIn in=field.getAnnotation(SpIn.class);
         	    field.setAccessible(true);
         	    if(field.getType()==Long.class){
         	    	proc.registerParameter(in.order(), Long.class, ParameterMode.IN).bindValue((Long)field.get(dto));
         	    }else if(field.getType()==String.class){
         		    proc.registerParameter(in.order(), String.class, ParameterMode.IN).bindValue((String)field.get(dto));
         	    }
            }else if(field.isAnnotationPresent(SpOut.class)){//设置输出参数
            	SpOut out=field.getAnnotation(SpOut.class);
            	if(field.getType()==String.class){
            		proc.registerParameter(out.order(), String.class, ParameterMode.OUT);
            	}else if(field.getType()==Long.class){
            		proc.registerParameter(out.order(), Long.class, ParameterMode.OUT);
            	}else if(field.getType()==Integer.class){
            		proc.registerParameter(out.order(), Integer.class, ParameterMode.OUT);
            	}
            }
		}
        Map<String, Object> map=new HashMap<>();
        ProcedureOutputs outputs=proc.getOutputs();
        for(int i=0, length=fields.length; i<length; ++i){
        	field=fields[i];
        	if(field.isAnnotationPresent(SpOut.class)){
        		SpOut out=field.getAnnotation(SpOut.class);
        		map.put(field.getName(), outputs.getOutputParameterValue(out.order()));
        	}
        }
        
		return new MapKit(map);
	}
	
	/**
	 * 执行返回list的存储过程
	 * 
	 * @param name
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> execProcList(String name, Object... args) throws Exception{
		final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		sessionFactory.getCurrentSession().doWork(new Work() {
			public void execute(Connection conn) throws SQLException {
				StringBuilder sql=new StringBuilder();
				sql.append("{CALL ").append(name).append("(");
				if(args!=null){
					for(int i=0, length=args.length, size=length-1; i<length; ++i){
						sql.append("?");
						if(i<size){
							sql.append(",");
						}
					}
				}
				sql.append(")}");
				CallableStatement call=conn.prepareCall(sql.toString());
				if(args!=null){
					for(int i=0, length=args.length; i<length; ++i){
						call.setObject(i+1, args[i]);
					}
				}
				ResultSet rs=call.executeQuery();
				ResultSetMetaData metaData=rs.getMetaData();
				int colCount=metaData.getColumnCount();
				while(rs.next()){
					Map<String, Object> map=new HashMap<>();
					for(int i=1; i<=colCount; i++){
						String colName = metaData.getColumnName(i);
						map.put(colName, rs.getObject(colName));
					}
					result.add(map);
				}
				call.close();
				rs.close();
			}
		});
        
        return result;
	}

	/**
	 * 将数据绑定到实体类
	 * 
	 * @param clazz
	 * @param obj
	 * @param map
	 * @throws Exception
	 */
	private <T> void reflex(Class<T> clazz, T obj, Map<String, Object> map) throws Exception {
		BeanInfo info=Introspector.getBeanInfo(clazz);
		PropertyDescriptor[] props=info.getPropertyDescriptors();
        PropertyDescriptor prop=null;
        Method method=null;
        Object value=null;
        for(int i=0, length=props.length; i<length; ++i){
        	prop=props[i];
        	value=map.get(prop.getName().toUpperCase());
        	if(value==null){
        		continue;
        	}
            method=prop.getWriteMethod();
            method.invoke(obj, BeanKit.str2type(prop.getPropertyType(), value.toString()));
        }
	}

}


 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部