论坛首页 入门技术论坛

这样设计dao合理吗?大家讨论讨论!(修改版)

浏览 12520 次
该帖已经被评为新手帖
作者 正文
   发表时间:2009-07-08   最后修改:2009-07-10
DAO

这是我设计的dao的类图,我想通过这样的设计(如下图),已经可以实现单一dao的功能。

  • 大小: 18.9 KB
   发表时间:2009-07-08  
发个我写的通用Dao 交流下



package com.market.b2c.suport.util.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.market.b2c.domain.commodity.Commodity;
import com.market.b2c.suport.db.DBFactory;

/**
* description
* author: zhangde
* date: Jul 3, 2009
*/
public class BaseDaoJdbcImpl implements BaseDao {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
public void save(Object object) {
StringBuffer sql = new StringBuffer("insert into ").append(object
.getClass().getSimpleName().toLowerCase());// 表名对应类名
sql.append(" (");
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
sql.append(fields[i].getName()).append(",");
}
sql.deleteCharAt(sql.length() - 1);
sql.append(") values (");
for (int i = 0; i < fields.length; i++) {
sql.append("?,");
}
sql.deleteCharAt(sql.length() - 1);
sql.append(")");
System.out.println(sql.toString());
conn = DBFactory.getConnection();
try {
ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < fields.length; i++) {
Object value = null;
String methodName = "get"+ fields[i].getName().substring(0, 1).toUpperCase()+ fields[i].getName().substring(1);
Method method = object.getClass().getMethod(methodName, null);
value = method.invoke(object, null);
ps.setObject(i + 1, value);
}
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
// Commodity commodity = new Commodity();
// //commodity.setId(new Integer(2));
// commodity.setName("commodity1");
BaseDao baseDao = new BaseDaoJdbcImpl();
// baseDao.save(commodity);
//
// Commodity commdoity2=(Commodity) baseDao.get(Commodity.class, new Integer(2));
// System.out.println(commdoity2.getName());
// System.out.println(commdoity2.getId());
//baseDao.delete(Commodity.class, new Integer(2));
// Commodity commodity=(Commodity) baseDao.getByProperty(Commodity.class, "name", "commodity1");
// System.out.println(commodity.getName());
// System.out.println(commodity.getId());
// List list=baseDao.findByProperty(Commodity.class, "name", "commodity1");
// System.out.println(list.size());
PropertyFinder finder=new PropertyFinder(Commodity.class);
finder.addParameter("name", "commodity1");
finder.addParameter("id", new Integer(30));
List list=baseDao.find(finder);
System.out.println(list.size());
}

public Object get(Class cls,Integer id) {
String sql="select * from "+cls.getSimpleName().toLowerCase()+" where id=?";
conn = DBFactory.getConnection();
Field[] fields = cls.getDeclaredFields();
Object object=null;
try {
ps = conn.prepareStatement(sql.toString());
ps.setInt(1, id.intValue());
rs=ps.executeQuery();
System.out.println(sql);
while(rs.next()){
if(object!=null)
throw new Exception("主键不唯一!");
Class clstmp=Class.forName(cls.getName());
object=clstmp.newInstance();
//组装参数
for(int i=0;i<fields.length;i++){
String field=fields[i].getName();
String methodName="set"+ field.substring(0, 1).toUpperCase()+ field.substring(1);
Class[] classs=new Class[1];
classs[0]=fields[i].getType();
Method method=cls.getMethod(methodName,classs);
method.invoke(object, new Object[]{rs.getObject(rs.findColumn(field))});
}
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}

public void delete(Class cls, Integer id) {
String sql="delete from " + cls.getSimpleName().toLowerCase()+" where id=?";
conn = DBFactory.getConnection();
try{
ps = conn.prepareStatement(sql.toString());
ps.setInt(1, id.intValue());
int row=ps.executeUpdate();
System.out.println(sql);
if(row==0)
throw new Exception("删除的行为0!");
}catch(Exception e){
e.printStackTrace();
}
}

public Object getByProperty(Class cls, String propertyName, Object value) {
String sql="select * from "+cls.getSimpleName().toLowerCase()+" where "+propertyName+"=?";
conn = DBFactory.getConnection();
Field[] fields = cls.getDeclaredFields();
Object object=null;
try {
ps = conn.prepareStatement(sql.toString());
ps.setObject(1, value);
rs=ps.executeQuery();
System.out.println(sql);
while(rs.next()){
if(object!=null)
throw new Exception("主键不唯一!");
Class clstmp=Class.forName(cls.getName());
object=clstmp.newInstance();
//组装参数
for(int i=0;i<fields.length;i++){

String methodName="set"+ fields[i].getName().substring(0, 1).toUpperCase()+ fields[i].getName().substring(1);
Class[] classs=new Class[1];
classs[0]=fields[i].getType();
Method method=cls.getMethod(methodName,classs);
method.invoke(object, new Object[]{rs.getObject(i+1)});
}
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}

public List findByProperty(Class cls, String propertyName, Object value) {
List result=null;
String sql="select * from "+cls.getSimpleName().toLowerCase()+" where "+propertyName+"=?";
conn = DBFactory.getConnection();
Field[] fields = cls.getDeclaredFields();
Object object=null;
try {
ps = conn.prepareStatement(sql.toString());
ps.setObject(1, value);
rs=ps.executeQuery();
System.out.println(sql);
while(rs.next()){
if(result==null)
result=new ArrayList();
Class clstmp=Class.forName(cls.getName());
object=clstmp.newInstance();
//组装参数
for(int i=0;i<fields.length;i++){
String methodName="set"+ fields[i].getName().substring(0, 1).toUpperCase()+ fields[i].getName().substring(1);
Class[] classs=new Class[1];
classs[0]=fields[i].getType();
Method method=cls.getMethod(methodName,classs);
method.invoke(object, new Object[]{rs.getObject(i+1)});
}
result.add(object);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

@Override
public List find(Finder finder) {
List result=null;
conn = DBFactory.getConnection();
Field[] fields = finder.getCls().getDeclaredFields();
Object object=null;
try {
ps = conn.prepareStatement(finder.getSql());
Map parameters=finder.getParameters();
Iterator iterator=parameters.keySet().iterator();
int k=1;
while(iterator.hasNext()){
String propertyName=(String) iterator.next();
ps.setObject(k++, parameters.get(propertyName));
System.out.println( parameters.get(propertyName));
}
System.out.println(finder.getSql());
rs=ps.executeQuery();

while(rs.next()){
if(result==null)
result=new ArrayList();
Class clstmp=Class.forName(finder.getCls().getName());
object=clstmp.newInstance();
//组装参数
for(int i=0;i<fields.length;i++){
String methodName="set"+ fields[i].getName().substring(0, 1).toUpperCase()+ fields[i].getName().substring(1);
Class[] classs=new Class[1];
classs[0]=fields[i].getType();
Method method=finder.getCls().getMethod(methodName,classs);
method.invoke(object, new Object[]{rs.getObject(i+1)});
}
result.add(object);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
0 请登录后投票
   发表时间:2009-07-08  
基于JDBC实现的
0 请登录后投票
   发表时间:2009-07-08  
package com.market.b2c.suport.util.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
* 属性查找器
* author: zhangde
* date:   Jul 5, 2009
*/
public class PropertyFinder implements Finder {
private Class cls;
private Map<String,Object> parameters;
private Map<String,Short> comparators;
public PropertyFinder(Class cls){
this.cls=cls;
}
public void addParameter(String name,Object value){
if(parameters==null)
parameters=new HashMap();
parameters.put(name, value);
}
public void addParameter(String name,Object value,short comparator){
if(parameters==null)
parameters=new HashMap();
parameters.put(name, value);
comparators.put(name, new Short(comparator));
}

@Override
public Map<String,Object> getParameters() {
return parameters;
}
@Override
public String getSql() {
StringBuffer sql=new StringBuffer("select * from ").append(cls.getSimpleName()).append(" where 1=1");
Iterator iterator=parameters.keySet().iterator();
while(iterator.hasNext()){
String propertyName=(String) iterator.next();
Short comparator=null;
if(comparators!=null)
comparator=comparators.get(propertyName);
sql.append(" and ").append(propertyName).append(conversionComparator(comparator)).append(" ? ");
}
return sql.toString();
}

private String conversionComparator(Short comparator){
if(comparator==null || comparator==Finder.EQ)
return " = ";
if(comparator.shortValue()==Finder.GT)
return " > ";
if(comparator.shortValue()==Finder.LS)
return " < ";
return null;
}
@Override
public Class getCls() {
return cls;
}
}
0 请登录后投票
   发表时间:2009-07-08  
我这个是基于Hibernate实现的
0 请登录后投票
   发表时间:2009-07-08  
标题党。。。。
0 请登录后投票
   发表时间:2009-07-08  
show一下AbstractBaseDao的代码:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.type.Type;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.f3.db.entity.AbstractHandleObj;

/**
 * 基础Dao接口,定义通用的操作
 * @author 08374
 * @version v2.4 2009/07/07
 *
 */
public abstract class AbstractBaseDao extends HibernateDaoSupport {
		
	/*对返回list进行定义,返回记录数,0不起作用*/
	private int top = 0;	
	
	public int getTop() {
		return top;
	}
	public void setTop(int top) {
		this.top = top;
	}

	/**
	 * 对于返回列表的方法,通过调用我来实现返回记录数的控制,
	 * 设置返回记录数,如若top为0不设置,使用完将top归0
	 */
	protected void setMaxResult() throws DataAccessException{
		if(this.getTop() > 0){
			getHibernateTemplate().setMaxResults(this.getTop());
			this.setTop(0);
		}
		
	}
	
	/**
	 * 保存AbstractHandleObj实体
	 * @param hobj 继承AbstractHandleObj抽象类的实体
	 * @return Serializable 主键
	 */
	public abstract Serializable save(AbstractHandleObj hobj) throws DataAccessException;
	
	/**
	 * 更新AbstractHandleObj实体
	 * @param hobj 继承AbstractHandleObj抽象类的实体
	 * @return 
	 */
	public abstract void update(AbstractHandleObj hobj) throws DataAccessException;
	
	/**
	 * 保存或更新AbstractHandleObj实体
	 * @param hobj 继承AbstractHandleObj抽象类的实体
	 */
	public abstract void saveOrUpdate(AbstractHandleObj hobj) throws DataAccessException;
	
	/**
	 * 保存或跟新实体集合Collection<AbstractHandleObj>
	 * 若实体已经存(根据主键判断)在则更新实体,则保存实体
	 * @param hobjList 继承AbstractHandleObj抽象类的实体集合
	 */
	public abstract void saveOrUpdateAll(Collection<AbstractHandleObj> hobjList)
	throws DataAccessException;
	
	/**
	 * 删除AbstractHandleObj实体
	 * @param hobj 继承AbstractHandleObj抽象类的实体
	 * @return
	 */
	public abstract void delete(AbstractHandleObj hobj)
		throws DataAccessException;
	
	/**
	 * 删除Collection<AbstractHandleObj>集合实体
	 * @param hobjList 继承AbstractHandleObj抽象类的实体集合
	 */
	public abstract void deleteAll(Collection<AbstractHandleObj> hobjList)
		throws DataAccessException;

	/**
	 * 根据主键值获得继承AbstractHandleObj的实体
	 * @param entityName 继承AbstractHandleObj抽象类的实体名称(注:包含包名)
	 * @param id 实体主键
	 * @return
	 */
	public abstract AbstractHandleObj findByID(String entityName, String id)
		throws DataAccessException;

/**略...*/
}
0 请登录后投票
   发表时间:2009-07-08  
能否将代码共享一下?万分感谢...
0 请登录后投票
   发表时间:2009-07-08  
发到我邮箱即可,再次万分感谢

inroroc@163.com
0 请登录后投票
   发表时间:2009-07-08  
..万能..
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics