java_jdbc_3层 解耦
Dao - 提供接口
DaoImpl - 实现
DaoFactory - 工厂模式获取实现
DaoExcetpion - jdbc异常处理 实现runtime exception类即可
TestDemo - 主函数
User - bean
daoconfig.properties - 配置文件
package cn.itcast.user; public interface Dao { public User findById(int id); }
package cn.itcast.user; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import cn.itcast.JdbcUtils; public class DaoImpl implements Dao { @Override public User findById(int id) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; User user=null; String sql = "select * from t_user where id=?"; try{ conn = JdbcUtils.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, id); rs=ps.executeQuery(); while(rs.next()){ user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("username")); user.setPassword(rs.getString("password")); } }catch(SQLException e){ throw new DaoExcetpion(e.getMessage(),e); }finally{ JdbcUtils.free(rs, ps, conn); } return user; } }
package cn.itcast.user; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class DaoFactory { private static Dao dao = null; private static DaoFactory intance = new DaoFactory(); private DaoFactory() { try { Properties prop = new Properties(); InputStream inStream = DaoFactory.class.getClassLoader().getResourceAsStream("daoconfig.properties"); prop.load(inStream); String userDaoClass = prop.getProperty("userDaoClass"); dao=(Dao)Class.forName(userDaoClass).newInstance(); } catch (Exception e) { // TODO Auto-generated catch block throw new ExceptionInInitializerError(e); } } public static DaoFactory getInstance() { return intance; } public Dao getUserDao() { return dao; } }
package cn.itcast.user; public class TestDemo { public static void main(String[] args) { // TODO Auto-generated method stub // Dao dao = new DaoImpl(); Dao dao = DaoFactory.getInstance().getUserDao(); User user = dao.findById(2); System.out.println(user.getId()); System.out.println(user.getName()); } }
//配置文件
userDaoClass=cn.itcast.user.DaoImpl