CodeWeblog.com » hashset,import java,java util » The operation of the database my base class (HIBERNATE)

The operation of the database my base class (HIBERNATE)

package com.huicui.util;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

import com.dudujava.model.HibernateSessionFactory;

/**
 *  
 * 
 * @author dudujava
 * 
 */
 
public class DBUtil {
	static Logger logger = Logger.getLogger(DBUtil.class.getName());

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {

	}

	public static Object findByID(String objfullname, int id) {
		try {
			return HibernateSessionFactory.getSession().get(objfullname.trim(),
					id);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return null;// TODO: handle exception
		}

	}

	public static Object findByID(String objfullname, String id) {
		Integer itemp = null;
		try {
			itemp = Integer.parseInt(id);
		} catch (Exception e) {
		logger.error(e);	// TODO: handle exception
		}

		return findByID(objfullname, itemp);
	}
 
	public static void modify(String sfullname, int id, Map map) {

		if (map.isEmpty())
			return;
		
		try {
			Object obj = findByID(sfullname, id);
			save(obj, map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(e);
			e.printStackTrace();
		}

	}
	public static void modify(String sfullname, String sid, Map map) {

		 
		modify(sfullname,Integer.parseInt(sid), map);
	}

	/**
	 * @param obj
	 */
	public static int save(Object obj) {

		Transaction tx = null;
		Session session = null;

		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Serializable sObj = session.save(obj);
			tx.commit();
			return (Integer.parseInt(sObj.toString()));
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			logger.error(e);
			return -1;
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}

	}

	/**
	 * @param obj
	 */
	public static void delete(Object obj) {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			logger.error(e);
			e.printStackTrace();
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}
	/**
	 * @param listobj POJO List
	 */
	@SuppressWarnings("unchecked")
	public static void delete(List listobj) { 
		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < listobj.size(); i++) {
				session.delete(listobj.get(i));	
			}
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}
	/**
	 * 
	 * @param sql  HQL 
	 *            eg:delete from User where Country.id=1;
	 */
	public static int modify(String sql) {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Query q = session.createQuery(sql);
			int itmep = q.executeUpdate();
			tx.commit();
			return itmep;
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}
	public static int modifyBYHql(String sql) {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Query q = session.createQuery(sql);
			int itmep = q.executeUpdate();
			tx.commit();
			return itmep;
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}

	public static int modifyBYsql(String sql) {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Query q = session.createSQLQuery(sql);
			int itmep = q.executeUpdate();
			tx.commit();
			return itmep;
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}
	/**
	 * @param classname
	 * @param sObjID
	 * @throws Exception
	 */
	public static void delete(String classname, String sObjID)
			throws  Exception {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Object obj = findByID(classname, sObjID);
			if (obj != null)
				session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			logger.error(e);
			e.printStackTrace();
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
	}

	public static void save(List list) {

		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < list.size(); i++) {
				session.save(list.get(i));
			}
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			logger.error(e);
		} finally {
			try {
				session.close();
			} catch (Exception e) {
			}
		}
		logger.debug("save successfull save object number:"+list.size());
	}

	@SuppressWarnings("unchecked")
	public static int save(String sname, Map map)  {

		Object objtemp = null;
		try {
			objtemp =Class.forName(sname.trim()).newInstance();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			logger.error(e1);
			e1.printStackTrace();
		}
		return DBUtil.save(objtemp,map);

	}
	
	@SuppressWarnings("unchecked")
	public static int save(String sname,String sid, Map map)  {

		Object objtemp = null;
		try {
			objtemp =findByID(sname,sid);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			logger.error(e1);
			e1.printStackTrace();
		}
		return DBUtil.save(objtemp,map);

	}

	@SuppressWarnings("unchecked")
	public static int save(Object objtemp, Map map) {

		String skey = "";
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {

			skey = it.next().toString().trim();
			if (skey.length() == 0) {
				logger.error("key  not allow NULL ,MAP:" + map);
				continue;
			}
			Object[] args = new Object[1];
			args[0] = map.get(skey);
			try {

				ReflectUtil.invokeMethod(objtemp, "set"
						+ skey.substring(0, 1).toUpperCase()
						+ skey.substring(1), args);

			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
				return -1;

			}
		}

		return DBUtil.save(objtemp);

	}

	public static List searchByHql(String sql) {
		return HibernateSessionFactory.getSession().createQuery(sql).list();

	}

	public static List searchBySql(String sql) {
		try {
			return HibernateSessionFactory.getSession().createSQLQuery(sql)
					.list();
		} catch (Exception e) {
		e.printStackTrace();	
		System.out.println("your input sql is incorrect!");
		// TODO: handle exception
		}
		return null;

	}

	@SuppressWarnings("unchecked")
	public static List search(String classname, Map map, int ibegin, int inum)
		 {

		List list = new ArrayList();
		Session session = null;
		Transaction tran = null;
			 
		try {
			session = HibernateSessionFactory.getSession();
			tran = session.beginTransaction();
			Criteria temp = session.createCriteria(Class.forName(classname));
		
			String skey = "";
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				Object obj = it.next();
				if (obj instanceof List) {
					List listTemp = (List) obj;
					for (int i = 0; i < listTemp.size(); i++) {
						temp = temp.add((Criterion) (listTemp.get(i)));
					}
					continue;
				}
				if (obj instanceof Order) {
					temp = temp.addOrder((Order) obj);
					continue;
				}

				skey = obj.toString();
				temp = temp.add(Expression.eq(skey, map.get(skey)));

			}
			temp.setFirstResult(ibegin);
			temp.setMaxResults(inum);
			list = temp.list();

		} catch (Exception e) {
		 
			// e.printStackTrace();
		} finally {

			session.close();
		}

		return list;

	}

	/**
	 * @param classname
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List search(String classname, Map map)  {
		List list = new ArrayList();
		Session session = null;
		Transaction tran = null;

		try {
			session = HibernateSessionFactory.getSession();
			Criteria temp = session.createCriteria(Class.forName(classname));
			if (map.isEmpty())
				return temp.list();
			String skey = "";
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				Object obj = it.next();
				if (obj instanceof List) {
					List listTemp = (List) obj;
					for (int i = 0; i < listTemp.size(); i++) {
						temp = temp.add((Criterion) (listTemp.get(i)));
					}
					continue;
				}
				if (obj instanceof Order) {
					temp = temp.addOrder((Order) obj);
					continue;
				}
				skey = obj.toString();
				temp = temp.add(Expression.eq(skey, map.get(skey)));

			}
			list = temp.list();

		} catch (Exception e) {
			logger.info(e);
			e.printStackTrace();
		} finally {

			session.close();

		}

		return list;

	}

	/**
	 * @param classname  POJO full name
	 * @param map  put restrictions   keys values
	 * @param sprefix  input data prefix
	 * @return  POJO list
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List search(String classname, Map map, String sprefix)
			  {
		List list = new ArrayList();
		Session session = null;
		Transaction tran = null;
		List pc = null;
		 
		try {
			session = HibernateSessionFactory.getSession();
			tran = session.beginTransaction();
			Criteria temp = session.createCriteria(Class.forName(classname));
			if (map.isEmpty())
				return temp.list();
			temp.setMaxResults(50);
			String skey = "";
			map = doFilter(map, sprefix);
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				Object obj = it.next();
				if (obj instanceof List) {
					List listTemp = (List) obj;
					for (int i = 0; i < listTemp.size(); i++) {
						temp = temp.add((Criterion) (listTemp.get(i)));
					}
					continue;
				}

				if (obj instanceof Order) {
					temp = temp.addOrder((Order) obj);
					continue;
				}

				skey = obj.toString();
				temp = temp.add(Expression.eq(skey, map.get(skey)));

			}
			list = temp.list();

		} catch (Exception e) {
			logger.info(e);
			// e.printStackTrace();
		} finally {

			session.close();
		}

		return list;

	}

	@SuppressWarnings("unchecked")
	public static Map doFilter(Map map) {
		return doFilter(map, "para");

	}

	@SuppressWarnings("unchecked")
	public static Map doFilter(Map map, String sprefix) {
		if (sprefix == null || sprefix.trim().length() == 0)
			sprefix = "para";
		return doFilter(map, sprefix, false);

	}

	@SuppressWarnings("unchecked")
	public static Map doFilter(Map map, String sprefix, boolean isModify) {
		if (map.isEmpty())
			return map;
		Map maptemp = new HashMap();
		for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
			Object objtemp = iterator.next();
			if (objtemp instanceof List) {
				maptemp.put(objtemp, objtemp);
				continue;
			}
			if (objtemp instanceof String) 
			{
				String str = objtemp.toString();
				if (!isModify) //////search donot care null empoty
				{
					Set set = new HashSet();
					set.add("-1");
					set.add("SELECT");

					if (set.contains(map.get(str).toString().trim()
							.toUpperCase())) {
						continue;
					}
					if (map.get(str).toString().trim().length() == 0)
						continue;
				}
				if (!str.trim().startsWith(sprefix + "_"))
					continue;
				
				String[] strset = str.split("_");
				if (strset.length < 3) {

				continue;
				}
				String stype = strset[2].trim();
				Object obj = null;
				String svalue=map.get(str).toString();
 
				boolean bempoty=(svalue.trim().length()==0);
				try {
					if (stype.equalsIgnoreCase("float"))
						{
						if(bempoty)
							obj=new Float(0.0f);
						else
						obj = Float.parseFloat(map.get(str).toString());
						}
					
					if (stype.equalsIgnoreCase("int")|| stype.equalsIgnoreCase("integer"))
						{
						if(bempoty)
							obj=new Integer(0);
						else
						obj = Integer.parseInt(map.get(str).toString());
						}
					if (stype.equalsIgnoreCase("double"))
						{
						if(bempoty)obj =new  Double(0.0d);
						else
						obj = Double.parseDouble(map.get(str).toString());
						}
					if (stype.equalsIgnoreCase("date")) {
						DateFormat df = DateFormat.getDateInstance();
						if(bempoty)obj = new Date();
						else
						obj = df.parse(map.get(str).toString());
					}
					if (stype.equalsIgnoreCase("string")
							|| stype.equalsIgnoreCase("str"))
						obj = map.get(str);
					
					maptemp.put(strset[1].trim(), obj);
				} catch (ParseException e) {

					e.printStackTrace();
				}
			}

		}

		return maptemp;

	}

}


Digg Technorati StumbleUpon Mixx del.icio.us Reddit BlinkList Furl YahooMyWeb feedburner

Tags: hashset (RSS), import java (RSS), java util (RSS), map (RSS), import org (RSS), object obj (RSS), public static void (RSS), serializable (RSS), criterion (RSS), apache log4j (RSS), main string (RSS), arraylist (RSS), expression (RSS), hashmap (RSS), iterator (RSS), java text (RSS), static int (RSS), null session (RSS), static object (RSS), sid (RSS)

Permalink: http://www.codeweblog.com/the-operation-of-the-database-my-base-class-hibernate/

Leave a reply