首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

帮见见这个dao

2012-10-24 
帮看看这个daopackage com.test.daoimport java.lang.reflect.Fieldimport java.lang.reflect.Invocatio

帮看看这个dao
package com.test.dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.test.util.DBUtil;
import com.test.GenericClass;


@SuppressWarnings("unchecked")
public class BaseDAO<T> implements DAO<T> {

private Class classs = GenericClass.getClass(this.getClass(), 0);

public void addOrUpdate(String sql, Object[] objects) {
}

public void del(String sql, Object[] objects) {
}

public T find(String where, Object[] objects) throws Exception {
Connection con = DBUtil.getConnection();
PreparedStatement ps = con.prepareStatement("select * from "
+ classs.getSimpleName() + where);
setPrames(ps, objects);
ResultSet rs = ps.executeQuery();
Field[] fields = classs.getDeclaredFields();
Method[] methods = classs.getDeclaredMethods();
T o = (T) classs.newInstance();
if (rs.next()) {
ext(rs, fields, methods, o);
}
return o;
}

public QueryResult<T> findAll(int frist, int max, String where,
Object[] objects) throws Exception {
QueryResult queryResult = new QueryResult();
Connection con = DBUtil.getConnection();
StringBuilder sql = new StringBuilder();
String wheres = (where == null || "".equals(where)) ? "" : " where "
+ where;
//如果frist 和max都为-1 就不需要分页
if (frist == -1 && max == -1) {
sql.append("select * from " + classs.getSimpleName());
sql.append(wheres);
} else {
sql
.append("select * from(select *,row_number() over(order by id) as rownumber from "
+ classs.getSimpleName()
+ " ) as s where rownumber between "
+ frist
+ " and " + max + "");
sql.append(" and " + where);
}
PreparedStatement ps = con.prepareStatement(sql.toString());
setPrames(ps, objects);
ResultSet rs = ps.executeQuery();
Field[] fields = classs.getDeclaredFields();
Method[] methods = classs.getDeclaredMethods();
List list = new ArrayList();
while (rs.next()) {
T o = (T) classs.newInstance();
ext(rs, fields, methods, o);
list.add(o);
}
queryResult.setRows(list);
ps = con.prepareStatement("select count(*) from "
+ classs.getSimpleName() + wheres);
setPrames(ps, objects);
rs = ps.executeQuery();
if (rs.next()) {
queryResult.setTotal(rs.getLong(1));
}
return queryResult;
}

private void ext(ResultSet rs, Field[] fields, Method[] methods, T o)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SQLException {
for (int i = 0; i < fields.length; i++) {
for (int j = 0; j < methods.length; j++) {
if (methods[j].getName().equalsIgnoreCase(
"set" + fields[i].getName())) {
if (fields[i].getType().getSimpleName().equals("int")) {
methods[j].invoke(o, rs.getInt(fields[i].getName()));
} else if (fields[i].getType().getSimpleName().equals(
"String")) {
methods[j].invoke(o, rs.getString(fields[i].getName()));
} else if (fields[i].getType().getSimpleName().equals(
"float")) {
methods[j].invoke(o, rs.getFloat(fields[i].getName()));
}
}
}
}
}

private void setPrames(PreparedStatement ps, Object[] objects)
throws SQLException {
if (objects != null && objects.length > 0) {
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
}
}

}
package com.test.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@SuppressWarnings("unchecked")
public class GenerieUtils {
public static Class getClass(Class class1, int index) {
Type type = class1.getGenericSuperclass();
if (!(type instanceof ParameterizedType)) {
return Object.class;
}
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
if (!(type instanceof Class)) {
return Object.class;
}
return (Class) types[index];
}
}
package com.test.dao;

import java.util.List;

public class QueryResult<T> {
private List<T> rows;
private long total;

public List<T> getRows() {
return rows;
}

public void setRows(List<T> rows) {
this.rows = rows;
}

public long getTotal() {
return total;
}

public void setTotal(long total) {
this.total = total;
}

}
增删改 不知道该怎么写好一点..........
本人学java还没一年 所以写的不好请见谅 package com.test.dao; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.test.util.DBUtil; import com.test.GenericClass; @SuppressWarnings("unchecked") public class BaseDAO<T> implements DAO<T> { private Class classs = GenericClass.getClass(this.getClass(), 0); public void addOrUpdate(String sql, Object[] objects) { } public void del(String sql, Object[] objects) { } public T find(String where, Object[] objects) throws Exception { Connection con = DBUtil.getConnection(); PreparedStatement ps = con.prepareStatement("select * from " + classs.getSimpleName() + where); setPrames(ps, objects); ResultSet rs = ps.executeQuery(); Field[] fields = classs.getDeclaredFields(); Method[] methods = classs.getDeclaredMethods(); T o = (T) classs.newInstance(); if (rs.next()) { ext(rs, fields, methods, o); } return o; } public QueryResult<T> findAll(int frist, int max, String where, Object[] objects) throws Exception { QueryResult queryResult = new QueryResult(); Connection con = DBUtil.getConnection(); StringBuilder sql = new StringBuilder(); String wheres = (where == null || "".equals(where)) ? "" : " where " + where; //如果frist 和max都为-1 就不需要分页 if (frist == -1 && max == -1) { sql.append("select * from " + classs.getSimpleName()); sql.append(wheres); } else { sql .append("select * from(select *,row_number() over(order by id) as rownumber from " + classs.getSimpleName() + " ) as s where rownumber between " + frist + " and " + max + ""); sql.append(" and " + where); } PreparedStatement ps = con.prepareStatement(sql.toString()); setPrames(ps, objects); ResultSet rs = ps.executeQuery(); Field[] fields = classs.getDeclaredFields(); Method[] methods = classs.getDeclaredMethods(); List list = new ArrayList(); while (rs.next()) { T o = (T) classs.newInstance(); ext(rs, fields, methods, o); list.add(o); } queryResult.setRows(list); ps = con.prepareStatement("select count(*) from " + classs.getSimpleName() + wheres); setPrames(ps, objects); rs = ps.executeQuery(); if (rs.next()) { queryResult.setTotal(rs.getLong(1)); } return queryResult; } private void ext(ResultSet rs, Field[] fields, Method[] methods, T o) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SQLException { for (int i = 0; i < fields.length; i++) { for (int j = 0; j < methods.length; j++) { if (methods[j].getName().equalsIgnoreCase( "set" + fields[i].getName())) { if (fields[i].getType().getSimpleName().equals("int")) { methods[j].invoke(o, rs.getInt(fields[i].getName())); } else if (fields[i].getType().getSimpleName().equals( "String")) { methods[j].invoke(o, rs.getString(fields[i].getName())); } else if (fields[i].getType().getSimpleName().equals( "float")) { methods[j].invoke(o, rs.getFloat(fields[i].getName())); } } } } } private void setPrames(PreparedStatement ps, Object[] objects) throws SQLException { if (objects != null && objects.length > 0) { for (int i = 0; i < objects.length; i++) { ps.setObject(i + 1, objects[i]); } } } } package com.test.util; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @SuppressWarnings("unchecked") public class GenerieUtils { public static Class getClass(Class class1, int index) { Type type = class1.getGenericSuperclass(); if (!(type instanceof ParameterizedType)) { return Object.class; } Type[] types = ((ParameterizedType) type).getActualTypeArguments(); if (!(type instanceof Class)) { return Object.class; } return (Class) types[index]; } } package com.test.dao; import java.util.List; public class QueryResult<T> { private List<T> rows; private long total; public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } }

没有缩进。。。汗。package com.test.dao;import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.Date;import java.util.List;import javax.annotation.Resource;import org.apache.commons.lang.StringUtils;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.criterion.CriteriaSpecification;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Order;import org.hibernate.criterion.Projections;import org.hibernate.criterion.Restrictions;import org.springframework.stereotype.Component;import org.springframework.util.Assert;import com.test.bean.Pager;import com.test.bean.Search;import com.test.bean.Pager.OrderType;/** * Dao接口实现 - 基类实现 * ======================================= * @author 作者姓名: * @version 创建时间:Apr 8, 2011 5:30:19 PM * ======================================= */@Componentpublic class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {private Class<T> entityClass;protected SessionFactory sessionFactory;@SuppressWarnings("unchecked")public BaseDaoImpl() {this.entityClass = null;//得到类的Class Class c = getClass(); //返回本类的父类,包含泛型参数信息 Type type = c.getGenericSuperclass(); if (type instanceof ParameterizedType) { Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments(); this.entityClass = (Class<T>) parameterizedType[0]; }}/** * 设置SessionFactory * @param sessionFactory - Hibernate的SessionFactory */@Resourcepublic void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}/** * 得到当前Session * @return Session - Hibernate的Session */protected Session getSession() {return sessionFactory.getCurrentSession();}/** * 保存实体对象 * @param entity - 实体 * @return PK - 实体分配后的ID */@SuppressWarnings("unchecked")public PK save(T entity) {Assert.notNull(entity, "entity is required");return (PK)getSession().save(entity);}/** * 根据ID获取实体对象(get方式) * @param id - 实体id * @return T - 实体对象 */@SuppressWarnings("unchecked")public T get(PK id) {Assert.notNull(id, "id is required");return (T)getSession().get(entityClass, id);}/** * 根据ID获取实体对象(load方式) * @param id - id * @return T - 实体对象 */@SuppressWarnings("unchecked")public T load(PK id) {Assert.notNull(id, "id is required");return (T)getSession().load(entityClass, id);}/** * 删除实体对象 * @param entity - 实体对象 */public void delete(T entity) {Assert.notNull(entity, "entity is required");getSession().delete(entity);}/** * 删除实体对象 * @param id - id */public void delete(PK id) {Assert.notNull(id, "entity is required");T entity = load(id);getSession().delete(entity);}/** * 更改实体对象 * @param entity - 实体对象 */public void update(T entity) {Assert.notNull(entity, "entity is required");getSession().update(entity);}/** * 根据ID数组获取实体对象集合. * @param ids - id数组 * @return List - 实体集合 */@SuppressWarnings("unchecked")public List<T> get(PK[] ids) {Assert.notEmpty(ids, "ids must not be empty");String hql = "from " + entityClass.getName() + " as model where model.id in(:ids)";return getSession().createQuery(hql).setParameterList("ids", ids).list();}/** * 根据属性名和属性值获取实体对象 * @param propertyName - 属性名 * @param value - 属性值 * @return T - 对象 */@SuppressWarnings("unchecked")public T get(String propertyName, Object value) {Assert.hasText(propertyName, "propertyName must not be empty");Assert.notNull(value, "value is required");String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";return (T) getSession().createQuery(hql).setParameter(0, value).uniqueResult();}/** * 根据属性名和属性值获取实体对象集合 * @param propertyName - 属性名 * @param value - 属性值 * @return List - 对象集合 */@SuppressWarnings("unchecked")public List<T> getList(String propertyName, Object value) {Assert.hasText(propertyName, "propertyName must not be empty");Assert.notNull(value, "value is required");String hql = "from " + entityClass.getName() + " as model where model." + propertyName + " = ?";return getSession().createQuery(hql).setParameter(0, value).list();}/** * 获取所有实体对象集合 * @return List - 实体集合 */@SuppressWarnings("unchecked")public List<T> getAll() {String hql = "from " + entityClass.getName();return getSession().createQuery(hql).list();}/** * 获取所有实体对象总数. * @return long - 实体对象总数 */public Long getTotalCount() {String hql = "select count(*) from " + entityClass.getName();return (Long) getSession().createQuery(hql).uniqueResult();}/** * 根据ID数组删除实体对象 * @param ids - id数组 */public void delete(PK[] ids) {Assert.notEmpty(ids, "ids must not be empty");for (PK id : ids) {T entity = load(id);getSession().delete(entity);}}/** * 根据Pager对象进行查询 * @param pager - 页面bean * @return Pager - 页面bean */public Pager findByPager(Pager pager) {if (pager == null) {pager = new Pager();}DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);return findByPager(pager, detachedCriteria);}/** * 根据Pager和DetachedCriteria对象进行查询 * @param pager - 页面bean * @param detachedCriteria - Hibernate的detachedCriteria * @return Pager - 页面bean */public Pager findByPager(Pager pager, DetachedCriteria detachedCriteria) {if (pager == null) {pager = new Pager();}Integer pageNumber = pager.getPageNumber();Integer pageSize = pager.getPageSize();String property = pager.getProperty();String keyword = pager.getKeyword();String orderBy = pager.getOrderBy();OrderType orderType = pager.getOrderType();Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());if (StringUtils.isNotEmpty(property) && StringUtils.isNotEmpty(keyword)) {String propertyString = "";if (property.contains(".")) {String propertyPrefix = StringUtils.substringBefore(property, ".");String propertySuffix = StringUtils.substringAfter(property, ".");criteria.createAlias(propertyPrefix, "model");propertyString = "model." + propertySuffix;} else {propertyString = property;}criteria.add(Restrictions.like(propertyString, "%" + keyword + "%"));}Integer totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();criteria.setProjection(null);criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);criteria.setFirstResult((pageNumber - 1) * pageSize);criteria.setMaxResults(pageSize);if (StringUtils.isNotEmpty(orderBy) && orderType != null) {if (orderType == OrderType.asc) {criteria.addOrder(Order.asc(orderBy));} else {criteria.addOrder(Order.desc(orderBy));}}pager.setTotalCount(totalCount);pager.setList(criteria.list());return pager;}/** * 根据Search和Pager来查询 * @param search - 查询bean * @param pager - 页面bean * @return Pager - 页面bean */public Pager searchByProperty(Search search, Pager pager){if (pager == null) {pager = new Pager();}if (search == null) {search = new Search();}Integer pageNumber = pager.getPageNumber();Integer pageSize = pager.getPageSize();String orderBy = pager.getOrderBy();OrderType orderType = pager.getOrderType();DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entityClass);Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());//循环取得条件(字符串类型)if(search.getStrProperty()!=null){for(int i=0; i < search.getStrProperty().size(); i++){String propertyStr = search.getStrProperty().get(i);String keywordStr = search.getStrKeyword().get(i);if (StringUtils.isNotEmpty(propertyStr) && StringUtils.isNotEmpty(keywordStr)) {criteria.add(Restrictions.like(propertyStr, "%" + keywordStr + "%"));}}}//循环取得条件(日期类型)if(search.getDateProperty()!=null){for(int i=0; i < search.getDateProperty().size(); i++){String propertyDate = search.getDateProperty().get(i);Date dateFrom = search.getDateFrom().get(i);Date dateTo = search.getDateTo().get(i);if (dateFrom != null && !"".equals(dateFrom) && dateTo != null && !"".equals(dateTo)) {criteria.add(Restrictions.between(propertyDate, dateFrom, dateTo));}}}//循环取得条件(整数类型)if(search.getIntProperty()!=null){for(int i=0; i < search.getIntProperty().size(); i++){String propertyInt = search.getIntProperty().get(i);Object intFrom = search.getIntFrom().get(i);Object intTo = search.getIntTo().get(i);if (intFrom != null && intTo != null) {criteria.add(Restrictions.between(propertyInt, intFrom, intTo));}}}Integer totalCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();criteria.setProjection(null);criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);criteria.setFirstResult((pageNumber - 1) * pageSize);criteria.setMaxResults(pageSize);//设定排序规则if (StringUtils.isNotEmpty(orderBy) && orderType != null) {if (orderType == OrderType.asc) {criteria.addOrder(Order.asc(orderBy));} else {criteria.addOrder(Order.desc(orderBy));}}pager.setTotalCount(totalCount);pager.setList(criteria.list());return pager;}/** * 刷新session. */public void flush() {getSession().flush();}/** * 清除Session */public void clear() {getSession().clear();}/** * 清除某一对象. */public void evict(Object object) {Assert.notNull(object, "object is required");getSession().evict(object);}/** * 根据属性名、修改前后属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true). * @param propertyName属性名称 * @param oldValue修改前的属性值 * @param oldValue修改后的属性值 * @return boolean */public boolean isUnique(String propertyName, Object oldValue, Object newValue) {Assert.hasText(propertyName, "propertyName must not be empty");Assert.notNull(newValue, "newValue is required");if (newValue == oldValue || newValue.equals(oldValue)) {return true;}if (newValue instanceof String) {if (oldValue != null && StringUtils.equalsIgnoreCase((String) oldValue, (String) newValue)) {return true;}}T object = get(propertyName, newValue);return (object == null);}/** * 根据属性名判断数据是否已存在. * @param propertyName属性名称 * @param value值 * @return boolean */public boolean isExist(String propertyName, Object value) {Assert.hasText(propertyName, "propertyName must not be empty");Assert.notNull(value, "value is required");T object = get(propertyName, value);return (object != null);}} 为什么啊?求解释,谢谢public class ProductDaoImpl implements ProductDao {private HibernateTemplate template;public HibernateTemplate getTemplate() {return template;}public void setTemplate(HibernateTemplate template) {this.template = template;}public void deleteProduct(Product product) {template.delete(product);}public void insertProduct(Product product) {template.save(product);}@SuppressWarnings("unchecked")public List<Product> queryAllProducts() {return template.find("from Product");}public Product queryProductById(Integer id) {return (Product)template.get(Product.class, id);}@SuppressWarnings("unchecked")public List<Product> queryProductByName(final String productName) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q=session.createQuery("from Product as p where p.productName = ? ");q.setString(0, productName);return q.list();}});}@SuppressWarnings("unchecked")public List<Product> queryProductByStatus(final Status status) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q=session.createQuery("from Product as p where p.status.id = ? ");q.setInteger(0, status.getId());return q.list();}});}public void updateProduct(Product product) {template.update(product);}@SuppressWarnings("unchecked")public List<Product> queryProductByProductType(final ProductType productType) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q=session.createQuery("from Product as p where p.productType.id=? ");q.setInteger(0, productType.getId());return q.list();}});}@SuppressWarnings("unchecked")public List<Product> queryAllProducts(final PageModel page) {Long size=(Long)template.find("select count(*) from Product as p order by p.id").get(0);page.setTotalCount(size.intValue());return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q=session.createQuery("from Product as p order by p.id");q.setFirstResult(page.getFirstResult());q.setMaxResults(page.getPageSize());return q.list();}});}@SuppressWarnings("unchecked")public List<Product> queryProductByName(final PageModel page,final String productName) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q1=session.createQuery("select count(*) from Product as p where p.productName = ? order by p.id");q1.setString(0, productName);page.setTotalCount(q1.executeUpdate());Query q2=session.createQuery("from Product as p where p.productName = ? order by p.id");q2.setString(0, productName);q2.setFirstResult(page.getFirstResult());q2.setMaxResults(page.getPageSize());return q2.list();}});}@SuppressWarnings("unchecked")public List<Product> queryProductByProductType(final PageModel page,final ProductType productType) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q1=session.createQuery("select count(*) from Product as p where p.productType.id = ? order by p.id");q1.setInteger(0, productType.getId());page.setTotalCount(q1.executeUpdate());Query q2=session.createQuery("from Product as p where p.productType.id = ? order by p.id");q2.setInteger(0, productType.getId());q2.setFirstResult(page.getFirstResult());q2.setMaxResults(page.getPageSize());return q2.list();}});}@SuppressWarnings("unchecked")public List<Product> queryProductByStatus(final PageModel page,final Status status) {return (List<Product>)template.execute(new HibernateCallback(){public Object doInHibernate(Session session)throws HibernateException, SQLException {Query q1=session.createQuery("select count(*) from Product as p where p.status.id = ? order by p.id");q1.setInteger(0, status.getId());page.setTotalCount(q1.executeUpdate());Query q2=session.createQuery("from Product as p where p.status.id = ? order by p.id");q2.setInteger(0, status.getId());q2.setFirstResult(page.getFirstResult());q2.setMaxResults(page.getPageSize());return q2.list();}});}

热点排行