jdbc学习----4.DAO及其实现类

    技术2023-12-05  98

    BaseDao编写

    public abstract class BaseDao { /** * 修改方法 */ public int update(Connection con,String sql,Object...args) { PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if(args.length > 0) { for(int i = 0;i < args.length;i ++) { ps.setObject(i+1, args[i]); } } return ps.executeUpdate(); } catch (Exception e) { System.out.println("出现异常了:"+e.getMessage()); return 0; }finally { if(ps != null) { try { ps.close(); } catch (SQLException e) { } } } } /** * 通用对象查询方法 */ public <T> T queryForObject(String sql, Class<T> clazz, Object... args) throws Exception { Connection connection = JdbcUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); //设置占位符 for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } ResultSet result = ps.executeQuery(); ResultSetMetaData metaData = result.getMetaData(); int count = metaData.getColumnCount(); T t = null; if (result.next()) { t = clazz.getDeclaredConstructor().newInstance(); for (int i = 0; i < count; i++) { Field field = clazz.getDeclaredField(metaData.getColumnLabel(i + 1)); field.setAccessible(true); field.set(t, result.getObject(i + 1)); } } return t; } /** * 通用集合查询方法 */ public <T> List<T> queryForObjectList(String sql, Class<T> clazz, Object... args) throws Exception { Connection connection = JdbcUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); if(args.length > 0) { //设置占位符 for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } ResultSet result = ps.executeQuery(); ResultSetMetaData metaData = result.getMetaData(); int count = metaData.getColumnCount(); T t = null; List<T> list = new ArrayList<>(); while (result.next()) { t = clazz.getDeclaredConstructor().newInstance(); for (int i = 0; i < count; i++) { Field field = clazz.getDeclaredField(metaData.getColumnLabel(i + 1)); field.setAccessible(true); field.set(t, result.getObject(i + 1)); } list.add(t); } return list; } }

    CustomerDao定义标准

    public interface CustomersDao { public void insert(Connection con,Customers customer); public void deleteById(Connection con,Integer id); public void updateById(Connection con,Customers customer); public Customers findById(Connection con,Integer id); public List<Customers> findAll(); }

    CustomerDaoImpl实现类

    public class CustomerDaoImpl extends BaseDao implements CustomersDao{ /** * 插入 */ @Override public void insert(Connection con, Customers customer) { String sql = "insert into customers(name,email,birth) values(?,?,?)"; this.update(con, sql, customer.getName(),customer.getEmail(),customer.getBirth()); } /** * 删除 */ @Override public void deleteById(Connection con, Integer id) { String sql = "delete from customers where id=?"; this.update(con, sql, id); } /** * 修改 */ @Override public void updateById(Connection con, Customers customer) { String sql = "update customers set name=?,email=?,birth=? where id=?"; this.update(con, sql, customer.getName(),customer.getEmail(),customer.getBirth(),customer.getId()); } /** * 查询单条记录 */ @Override public Customers findById(Connection con, Integer id) { String sql = "select * from customers where id=?"; try { return this.queryForObject(sql, Customers.class, id); } catch (Exception e) { System.out.println("出现异常了:"+e.getMessage()); return null; } } /** * 返回所有记录 */ @Override public List<Customers> findAll() { String sql = "select * from customers"; try { return this.queryForObjectList(sql, Customers.class, new Object[] {}); } catch (Exception e) { System.out.println("出现异常了:"+e.getMessage()); return null; } } }

    测试方法

    @Test public void daoTest() throws Exception { CustomersDao customerDao = new CustomerDaoImpl(); Connection con = JdbcUtils.getConnection(); Customers customer = new Customers(1,"张飞","zhangfei@qq.com",new Date()); customerDao.insert(con, customer);//测试插入 customerDao.deleteById(con, 3862);//测试删除 customerDao.updateById(con, customer);//测试修改 customer = customerDao.findById(con, 1);//测试查询 System.out.println("查询到的数据:"+customer); List<Customers> customerList = customerDao.findAll();//测试查询所有 System.out.println("查询到的集合:"+customerList); con.close(); }

    当然以上代码有些地方忘了关闭连接,可自行加上.

    DAO升级:父类采用泛型

    @SuppressWarnings("unchecked") public abstract class BaseDao<T> { private Class<T> clazz = null; { Type type = this.getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; Type[] arguments = paramType.getActualTypeArguments();//获取父类泛型参数 clazz = (Class<T>) arguments[0]; } /** * 修改方法 */ public int update(Connection con,String sql,Object...args) { PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if(args.length > 0) { for(int i = 0;i < args.length;i ++) { ps.setObject(i+1, args[i]); } } return ps.executeUpdate(); } catch (Exception e) { System.out.println("出现异常了:"+e.getMessage()); return 0; }finally { if(ps != null) { try { ps.close(); } catch (SQLException e) { } } } } /** * 通用对象查询方法 */ public T queryForObject(String sql, Object... args) throws Exception { Connection connection = JdbcUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); //设置占位符 for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } ResultSet result = ps.executeQuery(); ResultSetMetaData metaData = result.getMetaData(); int count = metaData.getColumnCount(); T t = null; if (result.next()) { t = (T) clazz.getDeclaredConstructor().newInstance(); for (int i = 0; i < count; i++) { Field field = clazz.getDeclaredField(metaData.getColumnLabel(i + 1)); field.setAccessible(true); field.set(t, result.getObject(i + 1)); } } return t; } /** * 通用集合查询方法 */ public List<T> queryForObjectList(String sql, Object... args) throws Exception { Connection connection = JdbcUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); if(args.length > 0) { //设置占位符 for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } ResultSet result = ps.executeQuery(); ResultSetMetaData metaData = result.getMetaData(); int count = metaData.getColumnCount(); T t = null; List<T> list = new ArrayList<>(); while (result.next()) { t = (T) clazz.getDeclaredConstructor().newInstance(); for (int i = 0; i < count; i++) { Field field = clazz.getDeclaredField(metaData.getColumnLabel(i + 1)); field.setAccessible(true); field.set(t, result.getObject(i + 1)); } list.add(t); } return list; } }
    Processed: 0.029, SQL: 9