项目开发DAO层的封装!

我对于DAO层封装的理解:

为了便于开发以及提高开发效率使用两个包,c3p0-0.9.1.2.jar以及commons-dbutils-1.3.jar

封装步骤:

1,创建连接工厂

public class ConnectionFactory {
 private static Properties prop = new Properties();
 private static DataSource ds = null;
 
 static{
  try {
   prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
   
   Class.forName(prop.getProperty("driver"));
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 
  //使用C3P0连接池
  try {
   ds = DataSources.pooledDataSource(DataSources.unpooledDataSource(prop.getProperty("url"),
     prop.getProperty("user"), prop.getProperty("password")));
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 public static Connection getConnection(){
  Connection conn = null;
  try {
   conn = ds.getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  
  return conn;
 }
}

2,创建DAOFactory(生产操作数据库实例)

 

ackage com.tjitcast.dao;

import java.io.IOException;
import java.util.Properties;

/**
 * Dao工厂
 * @author qiujy
 */
public class DaoFactory {
 private static Properties prop = new Properties();
 static{
  try {
   prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("dao.properties"));
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 private DaoFactory(){}
 
 public synchronized static <T> T getInstance(String daoName, Class<T> interfaceType) {
  T obj = null;
  
  String className = prop.getProperty(daoName);
  if(null == className || "".equals(className)){
   throw new DaoException("指定名称对应的实现类不存在!!!");
  }else{
   try {
    obj = interfaceType.cast(Class.forName(className).newInstance());
   } catch (InstantiationException e) {
    e.printStackTrace();
   } catch (IllegalAccessException e) {
    e.printStackTrace();
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   }
  }
  return obj;
 }
}

3,写实体类(Entity),JAVABEAN

4,接口编程 创建EntityDao

5,写实现类 EntityDaoImpl

6在业务层中调用操作数据库的相应方法

你可能感兴趣的:(DAO,数据库,properties,c3p0,String,Class)