DAO: data(base) access object用于与数据库进行交互
1.实体类Customer.java
package loey.java1.bean;
import java.sql.Date;
/*
* ORM编程思想 (object relational mapping)
* 一个数据表对应一个java类
* 表中的一条记录对应java类的一个对象
* 表中的一个字段对应java类的一个属性
*
*/
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
}
public Customer(int id, String name, String email, Date birth) {
super();
this.id = id;
this.name = name;
this.email = email;
this.birth = birth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", birth=" + birth + "]";
}
}
2.BaseDAO.java
/*
* DAO: data(base) access object
* 封装了针对于数据表的通用的操作
*/
public abstract class BaseDAO<T> {
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;
}
}
3.CustomerDAO.java
/*
* 此接口用于规范针对于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);
}
4.CustomerDAOImpl.java
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);
}
}
5.测试
package loey.java1.dao.junit;
import loey.DBCUtil.DBCUtil;
import loey.java1.bean.Customer;
import loey.java1.dao.CustomerDAOImpl;
import org.junit.Test;
import java.net.DatagramSocket;
import java.sql.Connection;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.List;
public class CustomerDAOImplTest {
private CustomerDAOImpl dao = new CustomerDAOImpl();
@Test
public void testInsert() {
Connection conn = null;
try {
conn = DBCUtil.getConnection();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse("1992-11-27");
Customer cust = new Customer(1, "朴灿烈", "pcy@163.com", new Date(date.getTime()));
dao.insert(conn, cust);
System.out.println("添加成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testDeleteById(){
Connection conn = null;
try {
conn = DBCUtil.getConnection();
int id = 24;
dao.deleteById(conn,id);
System.out.println("删除成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testUpade(){
Connection conn = null;
try {
conn = DBCUtil.getConnection();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse("1992-04-06");
Customer cust = new Customer(23,"边伯贤","bbx@163.com",new Date(date.getTime()));
dao.update(conn,cust);
System.out.println("修改成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testGetCustomerById(){
Connection conn = null;
try {
conn = DBCUtil.getConnection();
int id = 6;
Customer customer = dao.getCustomerById(conn, id);
System.out.println(customer);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testGetAll(){
Connection conn = null;
try {
conn = DBCUtil.getConnection();
int id = 6;
List<Customer> customers = dao.getAll(conn, id);
customers.forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testGetCount(){
Connection conn = null;
try {
conn = DBCUtil.getConnection();
Long count = dao.getCount(conn);
System.out.println("该表共有" + count + "人");
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCUtil.close(conn,null,null);
}
}
@Test
public void testGetMaxBirth() {
Connection conn = null;
try {
conn = DBCUtil.getConnection();
Date maxBirth = dao.getMaxBirth(conn);
System.out.println("最大的生日为:" + maxBirth);
} catch (Exception e) {
e.printStackTrace();
}finally{
DBCUtil.close(conn, null,null);
}
}
}