DAO:Data Access Object访问数据信息的类和接口,包括了对数据的CRUD(Create、Retrival、Update、 Delete),而不包含任何业务相关的信息。
有时也称作:BaseDAO
作用:为了实现功能的模块化,更有利于代码的维护和升级。
package com.atguigu3.dao;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.atguigu1.util.JDBCUtils;
/*
* DAO: data(base) access object
* 封装了针对于数据表的通用的操作
* DAO:Data Access Object访问数据信息的类和接口,包括了对数据的CRUD(Create、Retrival、Update、
* Delete),而不包含任何业务相关的信息。有时也称作:BaseDAO
* 作用:为了实现功能的模块化,更有利于代码的维护和升级。
*/
public abstract class BaseDAO<T> { //因为只是用于实现功能的类,故不需要实例化:abstract
private Class<T> clazz = null;
// public BaseDAO(){
//
// }
{ //不用背,当作一个功能性的模块:获取当前BaseDAO的子类继承的父类中的泛型
Type genericSuperclass = this.getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
Type[] typeArguments = paramType.getActualTypeArguments();//获取了父类的泛型参数
clazz = (Class<T>) typeArguments[0];//泛型的第一个参数
}
// 通用的增删改操作---version 2.0 (考虑上事务)
public int update(Connection conn, String sql, Object... args) {// sql中占位符的个数与可变形参的长度相同!
PreparedStatement ps = null;
try {
// 1.预编译sql语句,返回PreparedStatement的实例
ps = conn.prepareStatement(sql);
// 2.填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);// 小心参数声明错误!!
}
// 3.执行
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 4.资源的关闭
JDBCUtils.closeResource(null, ps);
}
return 0;
}
// 通用的查询操作,用于返回数据表中的一条记录(version 2.0:考虑上事务)
public T getInstance(Connection conn, String sql, Object... args) {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
// 获取结果集的元数据 :ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
// 通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if (rs.next()) {
T t = clazz.newInstance();
// 处理结果集一行数据中的每一个列
for (int i = 0; i < columnCount; i++) {
// 获取列值
Object columValue = rs.getObject(i + 1);
// 获取每个列的列名
// String columnName = rsmd.getColumnName(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
// 给t对象指定的columnName属性,赋值为columValue:通过反射
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(null, ps, rs);
}
return null;
}
// 通用的查询操作,用于返回数据表中的多条记录构成的集合(version 2.0:考虑上事务)
public List<T> getForList(Connection conn, String sql, Object... args) {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
// 获取结果集的元数据 :ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
// 通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
// 创建集合对象
ArrayList<T> list = new ArrayList<T>();
while (rs.next()) {
T t = clazz.newInstance();
// 处理结果集一行数据中的每一个列:给t对象指定的属性赋值
for (int i = 0; i < columnCount; i++) {
// 获取列值
Object columValue = rs.getObject(i + 1);
// 获取每个列的列名
// String columnName = rsmd.getColumnName(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
// 给t对象指定的columnName属性,赋值为columValue:通过反射
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(null, ps, rs);
}
return null;
}
//用于查询特殊值的通用的方法
public <E> E getValue(Connection conn,String sql,Object...args){
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
if(rs.next()){
return (E) rs.getObject(1);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(null, ps, rs);
}
return null;
}
}
package com.atguigu3.dao;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;
import com.atguigu2.bean.Customer;
/*
* 此接口用于规范针对于customers表的常用操作
*/
public interface CustomerDAO {
/**
*
* @Description 将cust对象添加到数据库中
* @author shkstart
* @date 上午11:00:27
* @param conn
* @param cust
*/
void insert(Connection conn,Customer cust);
/**
*
* @Description 针对指定的id,删除表中的一条记录
* @author shkstart
* @date 上午11:01:07
* @param conn
* @param id
*/
void deleteById(Connection conn,int id);
/**
*
* @Description 针对内存中的cust对象,去修改数据表中指定的记录
* @author shkstart
* @date 上午11:02:14
* @param conn
* @param cust
*/
void update(Connection conn,Customer cust);
/**
*
* @Description 针对指定的id查询得到对应的Customer对象
* @author shkstart
* @date 上午11:02:59
* @param conn
* @param id
*/
Customer getCustomerById(Connection conn,int id);
/**
*
* @Description 查询表中的所有记录构成的集合
* @author shkstart
* @date 上午11:03:50
* @param conn
* @return
*/
List<Customer> getAll(Connection conn);
/**
*
* @Description 返回数据表中的数据的条目数
* @author shkstart
* @date 上午11:04:44
* @param conn
* @return
*/
Long getCount(Connection conn);
/**
*
* @Description 返回数据表中最大的生日
* @author shkstart
* @date 上午11:05:33
* @param conn
* @return
*/
Date getMaxBirth(Connection conn);
}
package com.atguigu3.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;
import com.atguigu2.bean.Customer;
public class CustomerDAOImpl extends BaseDAO<Customer> implements CustomerDAO{
@Override
public void insert(Connection conn, Customer cust) {
String sql = "insert into customers(name,email,birth)values(?,?,?)";
update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth());
}
@Override
public void deleteById(Connection conn, int id) {
String sql = "delete from customers where id = ?";
update(conn, sql, id);
}
@Override
public void update(Connection conn, Customer cust) {
String sql = "update customers set name = ?,email = ?,birth = ? where id = ?";
update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth(),cust.getId());
}
@Override
public Customer getCustomerById(Connection conn, int id) {
String sql = "select id,name,email,birth from customers where id = ?";
Customer customer = getInstance(conn, sql,id);
return customer;
}
@Override
public List<Customer> getAll(Connection conn) {
String sql = "select id,name,email,birth from customers";
List<Customer> list = getForList(conn, sql);
return list;
}
@Override
public Long getCount(Connection conn) {
String sql = "select count(*) from customers";
return getValue(conn, sql);
}
@Override
public Date getMaxBirth(Connection conn) {
String sql = "select max(birth) from customers";
return getValue(conn, sql);
}
}
package com.atguigu3.dao.junit;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;
import org.junit.Test;
import com.atguigu4.util.JDBCUtils;
import com.atguigu2.bean.Customer;
import com.atguigu3.dao.CustomerDAOImpl;
public class CustomerDAOImplTest {
private CustomerDAOImpl dao = new CustomerDAOImpl();
@Test
public void testInsert() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Customer cust = new Customer(1, "于小飞", "xiaofei@126.com",new Date(43534646435L));
dao.insert(conn, cust);
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testDeleteById() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
dao.deleteById(conn, 13);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testUpdateConnectionCustomer() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Customer cust = new Customer(18,"贝多芬","beiduofen@126.com",new Date(453465656L));
dao.update(conn, cust);
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetCustomerById() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection3();
Customer cust = dao.getCustomerById(conn, 19);
System.out.println(cust);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetAll() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
List<Customer> list = dao.getAll(conn);
list.forEach(System.out::println);
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetCount() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Long count = dao.getCount(conn);
System.out.println("表中的记录数为:" + count);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetMaxBirth() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Date maxBirth = dao.getMaxBirth(conn);
System.out.println("最大的生日为:" + maxBirth);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
}
package com.atguigu3.dao.junit;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.Date;
import java.util.List;
import org.junit.Test;
import com.atguigu4.util.JDBCUtils;
import com.atguigu2.bean.Customer;
import com.atguigu3.dao.CustomerDAOImpl;
public class CustomerDAOImplTest {
private CustomerDAOImpl dao = new CustomerDAOImpl();
@Test
public void testInsert() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Customer cust = new Customer(1, "于小飞", "xiaofei@126.com",new Date(43534646435L));
dao.insert(conn, cust);
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testDeleteById() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
dao.deleteById(conn, 13);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testUpdateConnectionCustomer() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Customer cust = new Customer(18,"贝多芬","beiduofen@126.com",new Date(453465656L));
dao.update(conn, cust);
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetCustomerById() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection3();
Customer cust = dao.getCustomerById(conn, 19);
System.out.println(cust);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetAll() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
List<Customer> list = dao.getAll(conn);
list.forEach(System.out::println);
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetCount() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Long count = dao.getCount(conn);
System.out.println("表中的记录数为:" + count);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
@Test
public void testGetMaxBirth() {
Connection conn = null;
try {
conn = JDBCUtils.getConnection();
Date maxBirth = dao.getMaxBirth(conn);
System.out.println("最大的生日为:" + maxBirth);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, null);
}
}
}