Java实现-DAO 模式

DAO 模式

DAO (DataAccessobjects 数据存取对象)是指位于业务逻辑和持久化数据之间实现对持久化数据的访问。通俗来讲,就是将数据库操作都封装起来。

对外提供相应的接口

在面向对象设计过程中,有一些"套路”用于解决特定问题称为模式。
DAO 模式提供了访问关系型数据库系统所需操作的接口,将数据访问和业务逻辑分离对上层提供面向对象的数据访问接口。

从以上 DAO 模式使用可以看出,DAO 模式的优势就在于它实现了两次隔离。

  • 1、隔离了数据访问代码和业务逻辑代码。业务逻辑代码直接调用DAO方法即可,完全感觉不到数据库表的存在。分工明确,数据访问层代码变化不影响业务逻辑代码,这符合单一职能原则,降低了藕合性,提高了可复用性。
  • 2、隔离了不同数据库实现。采用面向接口编程,如果底层数据库变化,如由 MySQL 变成 Oracle 只要增加 DAO 接口的新实现类即可,原有 MySQ 实现不用修改。这符合 “开-闭” 原则。该原则降低了代码的藕合性,提高了代码扩展性和系统的可移植性。

一个典型的DAO 模式主要由以下几部分组成。

  • 1、DAO接口: 把对数据库的所有操作定义成抽象方法,可以提供多种实现。
  • 2、DAO 实现类: 针对不同数据库给出DAO接口定义方法的具体实现。
  • 3、实体类:用于存放与传输对象数据。
  • 4、数据库连接和关闭工具类: 避免了数据库连接和关闭代码的重复使用,方便修改。

代码部分:

DAO接口:

import java.util.List;
public interface PetDao {
	
    /**
     * 查询所有宠物
     */
    List<Pet> findAllPets() throws Exception;

}

DAO实现类:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class PetDaoImpl extends BaseDao implements PetDao {

	/**
	 * 查询所有宠物
	 */
	public List<Pet> findAllPets() throws Exception {
		Connection conn=BaseDao.getConnection();
		String sql="select * from pet";
		PreparedStatement stmt= conn.prepareStatement(sql);
		ResultSet rs=    stmt.executeQuery();
		List<Pet> petList=new ArrayList<Pet>();
		while(rs.next()) {
			Pet pet=new Pet(
					rs.getInt("id"),
					rs.getInt("owner_id"),
					rs.getInt("store_id"),
					rs.getString("name"),
					rs.getString("type_name"),
					rs.getInt("health"),
					rs.getInt("love"),
					rs.getDate("birthday")
					);
			petList.add(pet);
		}
		BaseDao.closeAll(conn, stmt, rs);
		return petList;
	}

}
import java.util.Date;
/**
 * 宠物实体类
 */
public class Pet {

	private Integer id;    
	private Integer ownerId; //主人ID
	private Integer storeId; //商店ID
	private String name; //姓名
	private String typeName; //类型
	private int health; //健康值
	private int love; //爱心值
	private Date birthday; //生日
	
	public Pet(Integer id, Integer ownerId, Integer storeId, String name, String typeName, int health, int love,
			Date birthday) {
		super();
		this.id = id;
		this.ownerId = ownerId;
		this.storeId = storeId;
		this.name = name;
		this.typeName = typeName;
		this.health = health;
		this.love = love;
		this.birthday = birthday;
	}

	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	public Integer getOwnerId() {
		return ownerId;
	}
	
	public void setOwnerId(Integer ownerId) {
		this.ownerId = ownerId;
	}
	
	public Integer getStoreId() {
		return storeId;
	}
	
	public void setStoreId(Integer storeId) {
		this.storeId = storeId;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getTypeName() {
		return typeName;
	}
	
	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}
	
	public int getHealth() {
		return health;
	}
	
	public void setHealth(int health) {
		this.health = health;
	}
	
	public int getLove() {
		return love;
	}
	
	public void setLove(int love) {
		this.love = love;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

}

连接数据库:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 连接数据库
 * @author Katrina
 *
 */
public class BaseDao {

	private static String driver="com.mysql.jdbc.Driver";
	private static String url="jdbc:mysql://127.0.0.1:3306/epet";
	private static String user="root";
	private static String password="root";

	static {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);    
	}

	public static void closeAll(Connection conn,Statement stmt,ResultSet rs) throws SQLException {
		if(rs!=null) {
			rs.close();
		}
		if(stmt!=null) {
			stmt.close();
		}
		if(conn!=null) {
			conn.close();
		}
	}


	public int executeSQL(String preparedSql, Object[] param) throws ClassNotFoundException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		/* 处理SQL,执行SQL */
		try {
			conn = getConnection(); // 得到数据库连接
			pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					pstmt.setObject(i + 1, param[i]); // 为预编译sql设置参数
				}
			}
			ResultSet num = pstmt.executeQuery(); // 执行SQL语句
		} catch (SQLException e) {
			e.printStackTrace(); // 处理SQLException异常
		} finally {
			try {
				BaseDao.closeAll(conn, pstmt, null);
			} catch (SQLException e) {    
				e.printStackTrace();
			}
		}
		return 0;
	}

}
发布了318 篇原创文章 · 获赞 147 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44458489/article/details/105558384
今日推荐