DAO模式简介:
DataAccessObject,数据存取对象,指位于业务逻辑和持久化数据之间实现对持久化数据的访问,通俗来讲,就是将数据库操作都封装起来,对外提供相应的接口
优点:
1、隔离了数据访问代码和业务代码,业务逻辑代码直接调用DAO方法即可,分工明确,数据访问层代码不影响业务逻辑代码,符合单一职能原则,降低耦合性,提高可复用性
2、隔离了不同数据库实现。采用面向接口编程,如果底层数据库变化,只需增加DAO接口的实现类即可,原有实现类不用修改,符合“”开-闭“”原则降低了耦合性,提高了代码可扩 展性和系统的可移植性。
组成部分:
DAO接口:把对数据库所有的操作定义为抽象方法,可以提供多种实现。
import java.util.List;
/**
* DAO接口:宠物
* @author 30869
*
*/
public interface IPetDao {
/**
* 保存宠物
* @param pet 宠物
* @return
*/
int sava(Pet pet);
/**
* 删除宠物
* @param pet 宠物
* @return
*/
int del(Pet pet);
/**
* 更新宠物
* @param pet 宠物
* @return
*/
int update(Pet pet);
/**
* 获得指定昵称的宠物,精确查询
* @param name 昵称
* @return 宠物
*/
Pet getByName(String name);
/**
* 获得指定id的Pet
* @param id 编号
* @return 宠物对象
*/
Pet getById(Integer id);
/**
* 获得指定昵称的宠物列表,模糊查询
* @param name 昵称
* @return 宠物列表
*/
List<Pet> findByName(String name);
/**
* 获得指定类型的宠物列表,模糊查询
* @param type 宠物类型
* @return 宠物列表
*/
List<Pet> findByType(String type);
/**
* 查询全部的Pet
* @return
*/
List<Pet> getAllPet();
}
DAO实现类:根据不同数据库给出DAO接口定义方法的具体实现
import java.util.List;
/**
* PetDAO基于MySql的实现类
*
* @author 30869
*
*/
public class PetDaoMysqlImpl extends BaseDao implements IPetDao {
@Override
public int sava(Pet pet) {
String preparedSql = "insert into `dog`(`name`,`typeId`) values(?,?)";
Object[] param = { pet.getName(), pet.getTypeId() };
return executeUpdate(preparedSql, param);
}
@Override
public int del(Pet pet) {
String preparedSql = "delete from `dog` where id=?";
Object[] param = { pet.getTypeId() };
return executeUpdate(preparedSql, param);
}
@Override
public int update(Pet pet) {
String preparedSql = "update `dog` set `masterId`=?,`name`=?,`typeId`=?,`health`=?"
+ ",`love`=?,`adoptTime`=?,`status`=? where `id`=?";
Object[] param = { pet.getMasterId(), pet.getName(), pet.getTypeId(),
pet.getHealth(), pet.getLove(), pet.getAdoptTime(),
pet.getStatus(), pet.getId() };
return executeUpdate(preparedSql, param);
}
@Override
public Pet getById(Integer id) {
String preparedSql = "select * from `dog` where `id`=?";
Object[] param = { id };
rs = executeQuery(preparedSql, param);
return getOnePetOfResultSet(rs);
}
@Override
public Pet getByName(String name) {
String preparedSql = "select * from `dog` where `name`=?";
Object[] param = { name };
rs = executeQuery(preparedSql, param);
return getOnePetOfResultSet(rs);
}
@Override
public List<Pet> findByName(String name) {
String preparedSql = "select * from `dog` where `name` like ?";
Object[] param = { "%"+name+"%" };
rs = executeQuery(preparedSql, param);
return getPetOfResultSet(rs);
}
@Override
public List<Pet> findByType(String type) {
String preparedSql = "select * from `dog` where `typeId`=(select `typeId` from `petType` where `petType`=?)";
Object[] param = { "%"+type+"%" };
rs = executeQuery(preparedSql, param);
return getPetOfResultSet(rs);
}
@Override
public List<Pet> getAllPet(){
String preparedSql = "select * from `dog`";
Object[] param =null;
rs=executeQuery(preparedSql, param);
return getPetOfResultSet(rs);
}
}
实体类:用于存放和传输对象数据
import java.io.Serializable;
/**
* 宠物类,属性和数据库中Pet表的字段一一对应
*
* @author 30869
*
*/
public class Pet implements Serializable{
private static final long serialVersionUID = -6079513472113573519L;
private Integer id;//宠物ID
private Integer masterId;//主人ID
private String name;//昵称
private Integer typeId;//类型ID
private Integer health;//健康值
private Integer love;//亲密度
private java.sql.Timestamp adoptTime;//领养时间
private String status;//状态(未领养和已领养)
public Pet() {
super();
}
public Pet(String name, Integer typeId) {
super();
this.name = name;
this.typeId = typeId;
}
public Pet(Integer id, Integer masterId, String name, Integer typeId,
Integer health, Integer love, java.sql.Timestamp adoptTime, String status) {
super();
this.id = id;
this.masterId = masterId;
this.name = name;
this.typeId = typeId;
this.health = health;
this.love = love;
this.adoptTime = adoptTime;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
数据连接和关闭工具类:避免数据库连接和关闭代码的重复使用,方便修改
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 封装了JDBC的连接、关闭等功能
*
* @author 30869
*
*/
public class BaseDao {
protected Connection con = null;// 三个引用为了方便其他类访问(继承类直接用)
protected PreparedStatement pstmt = null;
protected ResultSet rs = null;
private static String driver = "";
private static String url = "";
private static String user = "";
private static String password = "";
static{
init();
}
/**
* 初始化连接参数
*/
public static void init() {
Properties properties = new Properties();//资源配置文件对象
String configFile = "jdbc.properties";//资源配置文件路径
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(
configFile);//资源配置文件输入流
try {
properties.load(is);//从输入流中读取属性列表到资源配置文件对象
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");//获取资源配置文件value
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
}
/**
* 获取连接
*
* @return
*/
public Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 释放和关闭资源
*
* @param con
* 连接对象
* @param pstmt
* 语句对象
* @param rs
* 结果集对象
*/
public void clossAll(Connection con, Statement pstmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 增、删、改操作
*
* @param preparedSql
* 预编译的sql语句
* @param param
* 参数数组
* @return 受影响的行数
*/
public int executeUpdate(String preparedSql, Object[] param) {
Connection con = getConnection();
int n = 0;
try {
pstmt = con.prepareStatement(preparedSql);
if (param != null) {
for (int i = 0; i < param.length; i++) {
pstmt.setObject((i + 1), param[i]);
}
}
n = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
clossAll(con, pstmt, null);
}
return n;
}
/**
* 查询的通用方法
*
* @param preparedSql
* 预编译的sql语句
* @param param
* 参数数组
* @return 结果集
*/
public ResultSet executeQuery(String preparedSql, Object[] param) {
Connection con = getConnection();
try {
pstmt = con.prepareStatement(preparedSql);
if (param != null) {
for (int i = 0; i < param.length; i++) {
pstmt.setObject((i + 1), param[i]);
}
}
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}// 无需关闭,返回值需要被处理
return rs;
}
/**
* 从结果集中提取并返回查询结果为1的Pet
*
* @param rs
* @return
*/
public Pet getOnePetOfResultSet(ResultSet rs) {
Pet pet = null;
try {
if (rs.next()) {
pet = new Pet(rs.getInt(1), rs.getInt(2), rs.getString(3),
rs.getInt(4), rs.getInt(5), rs.getInt(6),
rs.getTimestamp(7), rs.getString(8));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
clossAll(con, pstmt, rs);
}
return pet;
}
/**
* 从结果集中取出Pet对象集合
*
* @param rs
* @return
*/
public List<Pet> getPetOfResultSet(ResultSet rs) {
Pet pet = null;
List<Pet> pets = new ArrayList<>();
try {
while (rs.next()) {
pet = new Pet(rs.getInt(1), rs.getInt(2), rs.getString(3),
rs.getInt(4), rs.getInt(5), rs.getInt(6),
rs.getTimestamp(7), rs.getString(8));
pets.add(pet);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
clossAll(con, pstmt, rs);
}
return pets;
}
/**
* 从结果集中取出1个Master对象
*
* @param rs
* @return
*/
public Master getOneMasterOfResultSet(ResultSet rs) {
Master master = null;
try {
if (rs.next()) {
master = new Master(rs.getInt(1), rs.getString(2),
rs.getString(3), rs.getInt(4));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
clossAll(con, pstmt, rs);
}
return master;
}
/**
* 从结果集中取出Master对象集合
*
* @param rs
* @return
*/
public List<Master> getMasterOfResultSet(ResultSet rs) {
Master master = null;
List<Master> masters = new ArrayList<>();
try {
while (rs.next()) {
master = new Master(rs.getInt(1), rs.getString(2),
rs.getString(3), rs.getInt(4));
masters.add(master);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
clossAll(con, pstmt, rs);
}
return masters;
}
/**
* 输出Pet集合信息
*
* @param pets
*/
public void showPet(List<Pet> pets) {
for (Pet pet : pets) {
System.out.println(pet.getId() + "\t" + pet.getMasterId() + "\t"
+ pet.getName() + "\t" + pet.getTypeId() + "\t"
+ pet.getHealth() + "\t" + pet.getLove() + "\t"
+ pet.getAdoptTime() + "\t" + pet.getStatus() + "\t");
}
}
}