Dao层模式

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、什么是DAO模式?

DAO(Data Access Object)模式就是写一个类,把访问数据库的代码封装起来。DAO在数据库与业务逻辑(Service)之间。

  1. 实体域,即操作的对象,例如我们操作的表是user表,那么就需要先写一个User类;

  2. DAO模式需要先提供一个DAO接口;

  3. 然后再提供一个DAO接口的实现类

  4. 再编写一个DAO工厂,Service通过工厂来获取DAO实现。

二、代码实现

 //User.java
public class User {
	private String uid;
	private String username;
	private String password;
    //… 省略get/set/toString等方法
}
//UserDao接口
public interface UserDao {
	public void add(User user);
	public void mod(User user);
	public void del(String uid);
	public User load(String uid);
	public List<User> findAll();
}
//UserDao实现类
public class UserDaoImpl implements UserDao {
	public void add(User user) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = JdbcUtils.getConnection();
			String sql = "insert into user value(?,?,?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getUid());
			pstmt.setString(2, user.getUsername());
			pstmt.setString(3, user.getPassword());
			pstmt.executeUpdate();
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}
	}

	public void mod(User user) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = JdbcUtils.getConnection();
			String sql = "update user set username=?, password=? where uid=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getUsername());
			pstmt.setString(2, user.getPassword());
			pstmt.setString(3, user.getUid());
			pstmt.executeUpdate();
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}		
	}

	public void del(String uid) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = JdbcUtils.getConnection();
			String sql = "delete from user where uid=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, uid);
			pstmt.executeUpdate();
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}			
	}

	public User load(String uid) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = JdbcUtils.getConnection();
			String sql = "select * from user where uid=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, uid);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				return new User(rs.getString(1), rs.getString(2), rs.getString(3));
			}
			return null;
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}	
	}

	public List<User> findAll() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = JdbcUtils.getConnection();
			String sql = "select * from user";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			List<User> userList = new ArrayList<User>();
			while(rs.next()) {
				userList.add(new User(rs.getString(1), rs.getString(2), rs.getString(3)));
			}
			return userList;
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			} catch(SQLException e) {}
		}	
	}
}

三、Jdbc事务

在jdbc中处理事务,都是通过Connection完成的!所以:同一事务中所有的操作,都在使用同一个Connection对象

3.1 JDBC中的事务

Connection的三个方法与事务相关:

  • setAutoCommit(boolean):设置是否为自动提交事务,如果true(默认值就是true)表示自动提交,也就是每条执行的SQL语句都是一个单独的事务,如果设置false,那么就相当于开启了事务了;con.setAutoCommit(false)表示开启事务!!!
  • commit():提交结束事务;con.commit();表示提交事务
  • rollback():回滚结束事务。con.rollback();表示回滚事务
jdbc处理事务的代码格式:
try {
  con.setAutoCommit(false);//开启事务….
  …
  con.commit();//try的最后提交事务
} catch() {
  con.rollback();//回滚事务
}

public void transfer(boolean b) {
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = JdbcUtils.getConnection();
			//手动提交
			con.setAutoCommit(false);
			String sql = "update account set balance=balance+? where id=?";
			pstmt = con.prepareStatement(sql);
			//操作
			pstmt.setDouble(1, -10000);
			pstmt.setInt(2, 1);
			pstmt.executeUpdate();
			
			// 在两个操作中抛出异常
			if(b) {
				throw new Exception();
			}
			pstmt.setDouble(1, 10000);
			pstmt.setInt(2, 2);
			pstmt.executeUpdate();
			
			//提交事务
			con.commit();
		} catch(Exception e) {
			//回滚事务
			if(con != null) {
				try {
					con.rollback();
				} catch(SQLException ex) {}
			}
			throw new RuntimeException(e);
		} finally {
			//关闭
			JdbcUtils.close(con, pstmt);
		}
	}

我们的jdbc默认是自动提交, 所以我们不需要手动提交了, 而且,在实际开发中,我们的事务是加在业务层,而不是加在DAO层

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值