欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用Java的反射和JPA写的工具类 博客分类: JavaSE JavaJPASQLHibernateSpring 

程序员文章站 2024-03-22 19:30:16
...
利用周末时间,花了近4个小时写了个‘万能’的CRUD工具类,不过要使用的话必须是用JPA来进行ORM操作。还有对象映射到数据表中时,Id字段必须是类名称的.LowerCase()+"Id"的形式,不过真的挺方便的。呵呵。水平有限,欢迎指教。
package com.evalution.model;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;


public class CRUDModel {
 
 /**
  * 获取对象列表,参数是要获取的对象的类型,目前是查出数据库的所有该对象的映射记录,
  * 但数据量大的话需要考虑分页等,以及查询的时候可能需要设置一些条件等
  * @param obj
  * @return
  */
 @SuppressWarnings("unchecked")
 public static List getObjectList(Object obj) {
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  List<Object> list = null;
  String className = obj.getClass().getSimpleName();
  String sql = "SELECT o FROM "+className+" o order by o."+className.toLowerCase()+"Id asc";
  Query query = em.createQuery(sql);
  list = query.getResultList();
  em.close();
  factory.close();
  return list;
 }
 
 /**
  * 保存对象,参数是要保存的对象
  * @param obj
  */
 public static void addObject(Object obj){
  
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  em.getTransaction().begin();
  em.persist(obj);
  em.getTransaction().commit();
  em.close();
  factory.close();
 }
 
 /**
  * 更新(修改)对象,参数是新对象和原对象的Id。
  * 即根据传入的Id,查处欲修改的对象,并将其修改为新传入的对象
  * @param sourceObj
  * @param id
  * @throws SecurityException
  * @throws IllegalArgumentException
  * @throws NoSuchMethodException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 public static void updateObject(Object sourceObj, int id) throws SecurityException, IllegalArgumentException, 
  NoSuchMethodException, IllegalAccessException, InvocationTargetException{
  
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  em.getTransaction().begin();
  Object targetObj = em.find(sourceObj.getClass(), id);
  CRUDModel.copyObjFromSourceToTarget(sourceObj,targetObj);
  em.getTransaction().commit();
  em.close();
  factory.close();
 }
 
 /**
  * 根据传入的对象类型和对象Id获取对象
  * @param obj
  * @param id
  * @return
  */
 public static Object getObjectById(Object obj,int id){
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  Object object = em.find(obj.getClass(), id);
  em.close();
  factory.close();
  return object;
 }
 
 /**
  * 注意该方法要求对象的主键必须为对象名的小写加Id的形式,即Object.toLowerCase()+"Id"
  * @param obj
  * @param id
  */
 public static void deleteObject(Object obj,int id){
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  em.getTransaction().begin();
  String className = obj.getClass().getSimpleName();
  Query query = em.createQuery("delete from "+className+" o where o."+className.toLowerCase()+"Id=:id");
  query.setParameter("id", id);
  query.executeUpdate();
  em.getTransaction().commit();
  em.close();
  factory.close();
 }
 
 /**
  * 本方法的功能是将源对象的属性值赋值给目标对象,要求源对象和目标对象是同一类型
  * @param sourceObj
  * @param targetObj
  * @return
  * @throws SecurityException
  * @throws NoSuchMethodException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 @SuppressWarnings("unchecked")
 public static Object copyObjFromSourceToTarget(Object sourceObj,Object targetObj) throws SecurityException, 
  NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
  
  if(!sourceObj.getClass().isInstance(targetObj)){
   System.out.println("两个对象不属同一类型,请核对....");
   return null;
  }
  
  //获取对象的Class,并得到其拥有的方法
  Class targetClass = targetObj.getClass();
  Method [] taregetMethods = targetClass.getDeclaredMethods();
  
  Class sourceClass = sourceObj.getClass();
  
  //遍历方法数组,过滤得到所有Set方法,给目标对象赋值
  for(int i = 0 ;i < taregetMethods.length;i++){
   
   String targetMethodName = taregetMethods[i].getName();
   
   if (targetMethodName.indexOf("set") != -1) {
    
    System.out.println("targetMethodName:"+targetMethodName);
    
    Method method =  targetClass.getMethod(targetMethodName,  taregetMethods[i].getParameterTypes());
    
    Object paramObj = new Object();
    
    //根据目标对象需要赋值的属性,从源对象中通过Get方法获取值
    Method method2 =  sourceClass.getMethod("get"+targetMethodName.substring(3, targetMethodName.length()),null);
    paramObj = method2.invoke(sourceObj, null);
    
    System.out.println("paramObj:"+paramObj);
    
    //将获取的值赋值给目标对象
    method.invoke(targetObj, paramObj);
   }
  }
  return targetObj;
 }
 
 /**
  * 根据传入的对象类型和参数列表以及起始和结束行数,获取结果集
  * @param obj 对象类型
  * @param map 给Sql传入的参数
  * @param start 起始行
  * @param end 结束行
  * @return
  */
 @SuppressWarnings("unchecked")
 public static List getObjectListWithParam(Object obj,HashMap<String, String> map,int start,int end) {
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  List<Object> list = null;
  String className = obj.getClass().getSimpleName();
  StringBuffer sql = new StringBuffer();
  sql.append("SELECT o FROM "+className+" o where 1=1");
  
  Object[] keySet = map.keySet().toArray();
  for (int i = 0; i < keySet.length; i++) {
   String key = (String)keySet[i];
   String value = (String)map.get(key);
   sql.append(" and o."+key+" = "+value);
  }
  sql.append(" order by o."+className.toLowerCase()+"Id asc");
  
  System.out.println(sql.toString());
  
  Query query = em.createQuery(sql.toString());
  if(start != -1 && end != -1){
   query.setFirstResult(start);
   query.setMaxResults(end);
  }
  list = query.getResultList();
  em.close();
  factory.close();
  return list;
 }
 
 /**
  * 获取总结果集的行数
  * @param obj
  * @return
  */
 public static int getRowCount(Object obj){
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  String sql = "select count(o) from "+obj.getClass().getSimpleName()+" o";
  Query query = em.createQuery(sql);
  Long count = (Long)query.getSingleResult();;
  em.close();
  factory.close();
  return count.intValue();
 }
 
 /**
  * 根据本地Sql返回执行的结果集
  * @param sql
  * @return
  */
 @SuppressWarnings("unchecked")
 public static List getObjectListWithNativeSql(String sql,Class resultClass){
  EntityManagerFactory factory = Persistence.createEntityManagerFactory("evalution");
  EntityManager em = factory.createEntityManager();
  List list = null;
  Query query = em.createNativeQuery(sql,resultClass);
  list = query.getResultList();
  em.close();
  factory.close();
  return list;
 }

}