如果可以请顺带把数据底层的连接代码也贴出来
求一个通用dao,牛点的注:并非作业贴 - -!

解决方案 »

  1.   

    这个没有通用之说
    这要看你的系统了
    定义相应的dao接口
    接口中定义相关的方法
      

  2.   


    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Properties;/*
     * 在本项目下新建个文本文件db.properties,内容如下:
     * 
     * drivername=oracle.jdbc.driver.OracleDriver
     * url=jdbc:oracle:thin:@172.16.0.126:1521:stu
     * username=ty0902b
     * password=tarena
     **/
    public class ConnectDB {
    private static Properties configDB;
    private ConnectDB(){}
    static {
    try{

    configDB=new Properties();
    configDB.load(new FileInputStream("./db.properties"));

    }catch(Exception ee){
    ee.printStackTrace();
    System.exit(1);
    }
    String driverName =configDB.getProperty("drivername");
    try {
    Class.forName(driverName);
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    } public static Connection getConnection() {
    String strURL = configDB.getProperty("url");
    String strUsername = configDB.getProperty("username");
    String strPwd = configDB.getProperty("password");
    Connection con = null;
    try {
    con = DriverManager.getConnection(strURL, strUsername, strPwd);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return con;
    } public static void close(ResultSet rs, Statement stmt, Connection con) {
    try {
    if (rs != null)
    rs.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    try {
    if (stmt != null)
    stmt.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    try {
    if (con != null)
    con.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }}
      

  3.   

    其实没有什么通用不通用 如果你没用HIBERNATE的话 那么你的SQL语句放哪? 没地方放..(或者你自己写个方法用来生成SQL语句 但你认为值得么?)如果用了HIBERNATE的话 他的DAO本来就是公用的(操作对象么 DAO也可以不知道对象是什么) 但无论怎么公共的DAO 使用这个DAO的类还是需要进行一些操作的(针对不同的表)
      

  4.   

    DAO没有通用的,要根据你的系统功能来定的!
      

  5.   

    其实hibernate自己就可以生成DAO的啊!
    以下就是一张表反转后的dao文件
    FinalTable是表名!import java.util.List;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.hibernate.LockMode;
    import org.hibernate.Query;
    import org.hibernate.criterion.Example;/**
     * A data access object (DAO) providing persistence and search support for
     * FinalTable entities. Transaction control of the save(), update() and delete()
     * operations can directly support Spring container-managed transactions or they
     * can be augmented to handle user-managed Spring transactions. Each of these
     * methods provides additional information for how to configure it for the
     * desired type of transaction control.
     * 
     * @see connection.FinalTable
     * @author MyEclipse Persistence Tools
     */public class FinalTableDAO extends BaseHibernateDAO {
    private static final Log log = LogFactory.getLog(FinalTableDAO.class); public void save(FinalTable transientInstance) {
    log.debug("saving FinalTable instance");
    try {
    getSession().save(transientInstance);
    log.debug("save successful");
    } catch (RuntimeException re) {
    log.error("save failed", re);
    throw re;
    }
    } public void delete(FinalTable persistentInstance) {
    log.debug("deleting FinalTable instance");
    try {
    getSession().delete(persistentInstance);
    log.debug("delete successful");
    } catch (RuntimeException re) {
    log.error("delete failed", re);
    throw re;
    }
    } public FinalTable findById(java.lang.Integer id) {
    log.debug("getting FinalTable instance with id: " + id);
    try {
    FinalTable instance = (FinalTable) getSession().get(
    "connection.FinalTable", id);
    return instance;
    } catch (RuntimeException re) {
    log.error("get failed", re);
    throw re;
    }
    } public List findByExample(FinalTable instance) {
    log.debug("finding FinalTable instance by example");
    try {
    List results = getSession().createCriteria("connection.FinalTable")
    .add(Example.create(instance)).list();
    log.debug("find by example successful, result size: "
    + results.size());
    return results;
    } catch (RuntimeException re) {
    log.error("find by example failed", re);
    throw re;
    }
    } public List findByProperty(String propertyName, Object value) {
    log.debug("finding FinalTable instance with property: " + propertyName
    + ", value: " + value);
    try {
    String queryString = "from FinalTable as model where model."
    + propertyName + "= ?";
    Query queryObject = getSession().createQuery(queryString);
    queryObject.setParameter(0, value);
    return queryObject.list();
    } catch (RuntimeException re) {
    log.error("find by property name failed", re);
    throw re;
    }
    } public List findAll() {
    log.debug("finding all FinalTable instances");
    try {
    String queryString = "from FinalTable";
    Query queryObject = getSession().createQuery(queryString);
    return queryObject.list();
    } catch (RuntimeException re) {
    log.error("find all failed", re);
    throw re;
    }
    } public FinalTable merge(FinalTable detachedInstance) {
    log.debug("merging FinalTable instance");
    try {
    FinalTable result = (FinalTable) getSession().merge(
    detachedInstance);
    log.debug("merge successful");
    return result;
    } catch (RuntimeException re) {
    log.error("merge failed", re);
    throw re;
    }
    } public void attachDirty(FinalTable instance) {
    log.debug("attaching dirty FinalTable instance");
    try {
    getSession().saveOrUpdate(instance);
    log.debug("attach successful");
    } catch (RuntimeException re) {
    log.error("attach failed", re);
    throw re;
    }
    } public void attachClean(FinalTable instance) {
    log.debug("attaching clean FinalTable instance");
    try {
    getSession().lock(instance, LockMode.NONE);
    log.debug("attach successful");
    } catch (RuntimeException re) {
    log.error("attach failed", re);
    throw re;
    }
    }
    }
      

  6.   

    hibernate就是公用的.使用hibernate吧!事半功倍!
      

  7.   

    先写一个baseDao继承hibernatesupport,然后业务Dao继承baseDao,业务Dao理获取base里的方法,使用HQL,QBC,SQL~
      

  8.   

    LZ你这不是在说hibernate么
    ~
      

  9.   

    我才晕捏。。lz到底是哪门意思啊?用hibernate不是可以轻松的实现的吗、
      

  10.   

    我知道Hibernate,我就是说底层的,不用Hibernate
    比如这个dao有增删改查的方法
    而这些增删改查对每张表是通用的
    那是不是除了,在CRUD的方法里提供一个String sql参数,就没有别的办法了?
    一般实际的项目里边是怎么写的?
    拿到是对每张表写一个dao?然后再这个dao里实现这张表的增删改查吗?其实说了半天我主要是想知道,怎么设计这个dao更合理,有效提高代码复用、符合开闭原则。
    所以想找一个好点的dao,学习学习
      

  11.   

    dao没用完全通用的,你可以做个BaseDao,让其他Dao来继承他,BaseDao里面做一些基础的增删改查,和分页
    我是这么做的
      import java.io.Serializable;
    import java.sql.SQLException;
    import java.util.List;import org.hibernate.Criteria;
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.criterion.DetachedCriteria;
    import org.hibernate.criterion.Projections;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.bluedot.commons.Constants;
    import com.bluedot.domain.Page;public class BaseDaoImpl<T extends Serializable> extends HibernateDaoSupport
    implements BaseDao<T> {
    protected Class clazz; public Class getClazz() {
    return clazz;
    } public void setClazz(Class clazz) {
    this.clazz = clazz;
    } public void delete(Object obj) {
    getHibernateTemplate().delete(obj);
    }
            //按主键查询
    public T get(Serializable id) {
    Object obj = getHibernateTemplate().get(clazz, id);
    return (T) obj;
    }
    public void insert(Object obj) {
    getHibernateTemplate().save(obj);
    }
            public void update(Object obj) {
    getHibernateTemplate().update(obj);
    }
    public Page pageByCriteria(final DetachedCriteria dc, int curPage) {
    Page p = new Page(); Integer sum = (Integer) getHibernateTemplate().execute(
    new HibernateCallback() {
    @Override
    public Object doInHibernate(Session s)
    throws HibernateException, SQLException {
    Criteria c = dc.getExecutableCriteria(s);
    c.setProjection(Projections.rowCount());
    return c.uniqueResult();
    }
    }); int totalPage = (int) Math.ceil(sum
    / Double.parseDouble(Constants.ITEM_PER_PAGE + ""));
    p.setTotalPage(totalPage); final int begin = (curPage - 1) * Constants.ITEM_PER_PAGE;
    List list = (List) getHibernateTemplate().execute(
    new HibernateCallback() { @Override
    public Object doInHibernate(Session s)
    throws HibernateException, SQLException {
    Criteria c2 = dc.getExecutableCriteria(s);
    c2.setFirstResult(begin);
    c2.setMaxResults(Constants.ITEM_PER_PAGE);
    return c2.list();
    }
    }); p.setResult(list);
    p.setCurrentPage(curPage);
    return p; }
    public Page pageByHql(String className, String whereClause, int curPage) {
    Page p = new Page();
    final String hql = "select count(*) from " + className + " "
    + whereClause; Integer sum = (Integer) getHibernateTemplate().execute(
    new HibernateCallback() {
    public Object doInHibernate(Session s)
    throws HibernateException, SQLException {
    Object obj = s.createQuery(hql).uniqueResult();
    return obj;
    }
    }); int totalPage = (int) Math.ceil(sum
    / Double.parseDouble(Constants.ITEM_PER_PAGE + ""));
    p.setTotalPage(totalPage); final int begin = (curPage - 1) * Constants.ITEM_PER_PAGE;
    final String findHql = "from " + className + " " + whereClause; List list = (List) getHibernateTemplate().execute(
    new HibernateCallback() { @Override
    public Object doInHibernate(Session s)
    throws HibernateException, SQLException {
    Query q2 = s.createQuery(findHql);
    q2.setFirstResult(begin);
    q2.setMaxResults(Constants.ITEM_PER_PAGE);
    return q2.list();
    }
    }); p.setResult(list);
    p.setCurrentPage(curPage);
    return p;
    } }
      

  12.   

    结合了大家的意见,我写了一个,大家给看看还有什么地方需要改进:
    package com.lj.dao;import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;public class BaseDAO {
    private static Connection conn = null;
    private static PreparedStatement pstmt = null;
    private static ResultSet rs = null;

    static{
    System.out.println("asdf");
    try {
    Context context = new InitialContext();
    context = (Context)context.lookup("java:comp/env/");
    DataSource ds = (DataSource)context.lookup("");
    conn = ds.getConnection();
    } catch (NamingException e) {
    System.out.println("------连接池上下文获取失败------");
    e.printStackTrace();
    } catch (SQLException e) {
    System.out.println("------获取Connection失败------");
    e.printStackTrace();
    }
    }

    /** 关闭所有连接 */
    public static void close(){
    if(rs != null){
    try {
    rs.close();
    } catch (SQLException e) {
    System.out.println("------ResultSet关闭异常------");
    e.printStackTrace();
    }
    }
    if(pstmt != null){
    try {
    pstmt.close();
    } catch (SQLException e) {
    System.out.println("------PreParedStatement关闭异常------");
    e.printStackTrace();
    }
    }
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException e) {
    System.out.println("------Connection关闭异常------");
    e.printStackTrace();
    }
    }
    }

    /**
     * 根据指定的sql语句进行查询
     * @param sql 执行的sql语句
     * @return 查询获得的结果集
     */

    public static ResultSet executeQuery(String sql){
    try {
    pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    rs = pstmt.executeQuery();
    } catch (SQLException e) {
    System.out.println("------执行查询时出错------");
    e.printStackTrace();
    }
    return rs;
    }

    /**
     * 根据指定的sql语句进行增删改操作
     * @param sql 执行的sql语句
     * @return 增删改操作后,受影响的行数
     */

    public static int executeUpdate(String sql){
    int count = 0;
    try {
    pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    count = pstmt.executeUpdate();
    } catch (SQLException e) {
    System.out.println("------执行增删改时出错------");
    e.printStackTrace();
    }
    return count;
    }
    }
    以后每张表的DAO可以这样写,我只写了一个方法:
    package com.lj.dao;import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;import com.lj.entity.User;public class UserDAO {
    public List getUsers(String sql){
    ResultSet rs = BaseDAO.executeQuery(sql);
    List<User> users = new ArrayList<User>();
    try {
    User user = null;
    while(rs.next()){
    user = new User();
    user.setId(rs.getInt("id"));
    user.setName(rs.getString("name"));
    user.setAge(rs.getInt("age"));
    user.setBirthday(rs.getDate("birthday"));
    users.add(user);
    }
    } catch (SQLException e) {
    System.out.println("------getUsers()方法进行查询时出错------");
    e.printStackTrace();
    }finally{
    BaseDAO.close();
    }
    return users;
    }
    }
      

  13.   

    LZ人才,通用dao,你具体是要干吗呢,总不能把所有的都贴上去吧,那肯定会弄跨论坛
      

  14.   

    不知道什么是通用DAO类的都是SB```鉴定完毕
      

  15.   

    我也在找一个比较牛B的通用的封装好的DAO类,搜索到了这个帖子,没想到这么多愣货,在不使用Struts不使用Hibernate 的前提下,就开发一些简单功能时,没有必要使用框架等技术,这就需要自己 编写一些重用性高的类。米想到还有这么多无知的人。难道开发个小网站也用框架?真是小牛拉大车。开发小B/S应用程序,如果还要用框架,就相当于一个小公司,职位还要分的像一个大企业一样细致?难道不累?效率能高吗?
    以下是通用的DAO类,虽然封装的并不完美,但重用性还是非常高的。希望有牛人能给个封闭更好的通用DAO。对了,解释一下,所谓通用DAO,就是直接copy就可以适用于任何一个工程中。
    import java.util.*;import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;import javax.servlet.jsp.jstl.sql.ResultSupport;
    import javax.servlet.jsp.jstl.sql.Result;import java.sql.SQLException;
    public class SQLCommandBean {

    private Connection connection; //连接对象
    private String sqlValue; //存储SQL语句
    private List values; //存储SQL语句的多个参数列表

    //设置连接
    public void setConnection(Connection connection){
    this.connection = connection;
    }

    //设定SQL语句的一个参数
    public void setSqlValue(String sqlValue){
    this.sqlValue = sqlValue;
    }

    //设定SQL语句的多个参数列表
    public void setValues(List Values){
    this.values = Values;
    }


    //将多个参数列表的值设置到SQL语句相应的位置上
    private void setSQLParameter(PreparedStatement pStatement, List values)
    throws SQLException {
    for(int i=0; i<values.size(); i++){
    Object obj = values.get(i);
    pStatement.setObject(i+1, obj);
    }
    }

    //执行查询语句,返回ResultSet对象结果集
    public Result executeQuery() throws SQLException {
    Result result = null;
    ResultSet resultSet = null;
    PreparedStatement pStatement = null;
    Statement statement = null;

    try{
    if(values != null && values.size() > 0){
    pStatement = connection.prepareStatement(sqlValue);
    setSQLParameter(pStatement, values);
    resultSet = pStatement.executeQuery();
    }else{
    statement = connection.createStatement();
    resultSet = statement.executeQuery(sqlValue);
    }

    result = ResultSupport.toResult(resultSet);
    }catch(SQLException se) {
    se.printStackTrace();
    }finally {
    if(resultSet != null){
    try{
    resultSet.close();
    resultSet =null;
    }catch(SQLException se){
    se.printStackTrace();
    }
    }

    if(statement != null){
    try{
    statement.close();
    statement = null;
    }catch(SQLException se){
    se.printStackTrace();
    }
    }

    if(pStatement != null){
    try{
    pStatement.close();
    pStatement = null;
    }catch(SQLException se){
    se.printStackTrace();
    }
    }

    if(connection != null && (!connection.isClosed())){
    try{
    connection.close();
    }catch(SQLException se){
    se.printStackTrace();
    }
    }
    }

    return result;
    }



    //执行Update语句
    public int executeupdate() throws SQLException {
    int returnRows = 0;
    PreparedStatement pStatement = null;
    Statement statement = null;

    try{
    if(values !=null && values.size() > 0){
    pStatement = connection.prepareStatement(sqlValue);
    setSQLParameter(pStatement, values);
    returnRows = pStatement.executeUpdate();
    }else{
    statement = connection.createStatement();
    returnRows = statement.executeUpdate(sqlValue);
    }
    }catch(SQLException se){
    se.printStackTrace();
    }finally {
    if(statement != null){
    try{
    statement.close();
    statement = null;
    }catch(SQLException se){
    se.printStackTrace();
    }
    }

    if(pStatement != null){
    try{
    pStatement.close();
    pStatement = null;
    }catch(SQLException se){
    se.printStackTrace();
    }
    }

    if(connection != null && (!connection.isClosed())){
    try{
    connection.close();
    }catch(SQLException se){
    se.printStackTrace();
    }
    }
    }

    return returnRows;
    }}
      

  16.   

    这个DAO效果非常好我们老师就是写的这个东西给我们的,他是武汉软件园的项目经理,我相信他的眼光
      

  17.   


    你这个dao是会报异常的,你关闭了connection后返回的result就不可用了,我用的是cachedroset替代