1. 程式人生 > >JDBC(3)JAVA連線資料庫之 抽象DAO操作

JDBC(3)JAVA連線資料庫之 抽象DAO操作

抽象DAO操作

  • 關於所有的表操作都會對應一些操作,我們都會把這些抽取到對應的DAO中。那麼存在大量的重複操作,是否可以抽出通用的部分,供大家繼承使用。
  • 把DAO的操作先寫成介面,把通用的操作提煉出來。
  • 實現操作
    • 根據主鍵查詢
    • 查詢所有
    • 增加、刪除、修改、記錄

抽象出DAO操作的介面

package lesson2.dao;

import java.io.Serializable;
import java.util.List;

/**
 * 抽象出DAO操作的介面
 * @author hh
 *
 * @param <T>
 */
public interface
Dao<T> {
public T findById(Serializable id,String sql,RowMapper<T> rm); public List<T> find(String sql,RowMapper<T> rm,Object...obj); public int saveOrUpdateOrDelete(String sql,Object...obj); }

實現介面

package lesson2.dao;

import java.io.Serializable;
import
java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import lesson2.JdbcUitl; /** * 實現介面,重寫抽象DAO的方法 * @author hh * * @param <T> */ public class DaoSupport<T> implements Dao<T>{ /** * 根據ID查詢物件 */
@Override public T findById(Serializable id,String sql,RowMapper<T> rm) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; T t=null; try { con = JdbcUitl.getConn(); pstmt = con.prepareStatement(sql); pstmt.setObject(1, id); rs = pstmt.executeQuery(); if(rs.next()){ //提煉介面-->在具體的表中才知道如何包裝 t = rm.getRow(rs); } } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUitl.close(pstmt, rs); } return t; } /** * 不定查詢 */ @Override public List<T> find(String sql, RowMapper<T> rm, Object... obj) { List<T> lists = new ArrayList<T>(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUitl.getConn(); pstmt = con.prepareStatement(sql); for(int i = 0;i<obj.length;i++){ pstmt.setObject(i+1, obj[i]); } rs=pstmt.executeQuery(); while(rs.next()){ T t = rm.getRow(rs); lists.add(t); } } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUitl.close(pstmt, rs); } return lists; } /** * 增加記錄 */ @Override public int saveOrUpdateOrDelete(String sql, Object... obj) { Connection con = null; PreparedStatement pstmt = null; int n = 0; try { con = JdbcUitl.getConn(); pstmt = con.prepareStatement(sql); for(int i=0;i<obj.length;i++){ pstmt.setObject(i+1,obj[i]); } n=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUitl.close(pstmt, null); } return n; } }

RowMapper 介面

由於無法得到具體的返回值型別,所以需要在具體厚獲得資料庫返回值後在決定。先定義介面,在之後的程式中實現。

ackage lesson2.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface RowMapper <T> {
    public T getRow(ResultSet rs)throws SQLException;
}

測試類1 Account類

package lesson2.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import lesson2.Account;
import lesson2.User;
import lesson2.dao.UserTest.UserMapper;

public class AccountTest {
    public static void main(String[] args) {
        DaoSupport<Account> dao = new DaoSupport<Account>();
        //測試根據id查詢
//      Account account=dao.findById(1001, "select*from account where id = ?",new AccountMapper());
//      System.out.println(account);
        //測試不定查詢
//      List<Account> accounts = dao.find("select * from account where money=?and id=?", new AccountMapper(), 100,1010);
//      for (Account account : accounts) {
//          System.out.println(account);
//      }
        //測試增加記錄
        Account account = new Account(4000, 1000, "hh");
        int n = dao.saveOrUpdateOrDelete("insert into account(id,money,name)values(?,?,?)", account.getId(),account.getMoney(),account.getName());
        System.out.println(n);


    }

    /**
     * 描述物件結構
     * @author hh
     *
     */
    static class AccountMapper implements RowMapper<Account>{

        @Override
        public Account getRow(ResultSet rs) throws SQLException {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setMoney(rs.getInt("money"));
            account.setName(rs.getString("name"));
            return account;
        }
    }
}

測試類2 User類

package lesson2.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import lesson2.User;

public class UserTest {
    public static void main(String[] args) {
        DaoSupport<User> dao= new DaoSupport<User>();
        //測試根據id查詢
//      User u = dao.findById(1001,"select * from bb_user where id = ?",new UserMapper());
//      System.out.println(u);
        //測試不定查詢
//      List<User> users = dao.find("select * from bb_user where username=?", new UserMapper(), "zhangsan");
//      for (User user : users) {
//          System.out.println(user);
//      }
        //測試增加記錄
        User user = new User(3000, "XXX", "YYY", "ZZZ");
        int n =dao.saveOrUpdateOrDelete("insert into bb_user(id,username,userpass,email)values(?,?,?,?)",user.getId(),user.getUsername(),user.getUserpass(),user.getEmail());
        System.out.println(n);
    }

    /**
     * 描述物件結構
     * @author hh
     *
     */
    static class UserMapper implements RowMapper<User>{

        @Override
        public User getRow(ResultSet rs) throws SQLException {
            // TODO Auto-generated method stub
            User u = new User();
            u.setId(rs.getInt("id"));
            u.setUsername(rs.getString("username"));
            u.setUserpass(rs.getString("userpass"));
            u.setEmail(rs.getString("email"));
            return u;
        }

    }
}