自己写的一个简单的basedao

首先说一段废话:

     1、以前没写过博客,不知道怎么写;

     2、我写的这个是有幸看了尚学堂马士兵老师的视频,最近做自己的毕业设计,用的jsp,servlet,所以脑袋一抽,就自己模仿马老师模拟hibernate那一段写的。

     3、我不是打广告的,不过火这么大只看马老师的视频,声音好。

     4、我可能水平太次,所以这个东西给初学者看的,大神可以指点,但不要喷谢谢!


下面是代码:


package com.zhao.dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zhao.model.Pager;
import com.zhao.model.SystemContext;
import com.zhao.util.BaseDaoUtil;
import com.zhao.util.DB;

public class BaseDao {
    
    public  <T> boolean add(T t){
        
        Field[] fields = BaseDaoUtil.getFields(t);
        String tableName = BaseDaoUtil.getTableName(t);
        String sql = "insert into "+ tableName + " values(null,";
        for(int i = 1; i < fields.length; i++){
            
            if(i < (fields.length - 1)){
                sql += "?,";
            }else{
                sql += "?)";
            }
        }
System.out.println("basedao: " + sql);
        Connection conn = DB.getConn();
        PreparedStatement pstmt = DB.getPStmt(conn, sql);
        
        try {
            BaseDaoUtil.save(pstmt, t);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            DB.close(pstmt);
            DB.close(conn);
        }
        
        return true;
    }

    public  <T> boolean delete(int id, T t) {
        
        String tableName = BaseDaoUtil.getTableName(t);
        String sql = "delete from " + tableName + " where id = '" + id + "'";
System.out.println("basedao:" + sql);
        Connection conn = DB.getConn();
        DB.executeUpdate(conn, sql);
        return true;
    }
    
    public  <T> boolean update(T t) {
        Connection conn = DB.getConn();
        PreparedStatement pstmt = null;
        String tableName = BaseDaoUtil.getTableName(t);
        try {
            
            String sql = "update " + tableName + " set ";
            //拿到实体类中所有的属性,全部set,前台界面控制不能set的
            Field[] fields = BaseDaoUtil.getFields(t);
            int paramSize = fields.length;
            
            //拼接sql
            for(int i = 1; i < paramSize; i++){
                if(i < paramSize - 1){
                    sql += fields[i].getName() + "=?,";
                }else{
                    sql += fields[i].getName() + "=? ";
                }
            }
            sql += "where id = ?";
           
    
System.out.println("basedao:" + sql);
            
            pstmt = DB.getPStmt(conn, sql);
            //set的值
            BaseDaoUtil.save(pstmt, t);
            
            //设置where条件的id值
            Method m = t.getClass().getMethod("getId");
            Class type = m.getReturnType();
            pstmt.setInt(paramSize, (Integer) (t.getClass().getMethod("getId")).invoke(t));
            pstmt.executeUpdate();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        } finally {
            DB.close(pstmt);
            DB.close(conn);
        }
        return true;
    }    
    
    public <T> T loadById(T t, int id) {
        
        String tableName = BaseDaoUtil.getTableName(t);
        
        String sql = "select * from " + tableName + " where id = " + id;
System.out.println("basedao:" + sql);
        Connection conn = DB.getConn();
        ResultSet rs = DB.executeQuery(conn, sql);
        try {
            BaseDaoUtil.load(t, rs);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DB.close(rs);
            DB.close(conn);
        }
        return t;
    }

    public  <T> T loadByName(T t, String name) {
        
        String tableName = BaseDaoUtil.getTableName(t);

        String sql = "select * from " + tableName + " where name = '" + name + "'";
System.out.print("basedao:" + sql);
        Connection conn = DB.getConn();
        ResultSet rs = DB.executeQuery(conn, sql);
        try {
            BaseDaoUtil.load(t, rs);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DB.close(rs);
            DB.close(conn);
        }
        return t;
    }
 
    
    public <T> List<T> listAll(T t){
        // TODO Auto-generated method stub
                String tableName =BaseDaoUtil.getTableName(t);                
                String sql = "select * from " + tableName ;
                
                Connection conn = DB.getConn();
                ResultSet rsCount = null;
                ResultSet rs = null;
                List<T> list = new ArrayList<T>();
                try {
                    
                    rs = DB.executeQuery(conn, sql);
                    BaseDaoUtil.list(t, rs, list);
            
                }catch(SQLException e){
                    e.printStackTrace();
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    DB.close(rsCount);
                    DB.close(rs);
                    DB.close(conn);
                }
            return list;
    }
}



package com.zhao.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;


2、这个是配合basedao使用的,分开俩个写原因是,以后碰到dao层自己独有的方法,也可以调用这里面的方法去保存
public class BaseDaoUtil {
    
    //拿到model所有属性,包括继承的属性
    public static <T> Field[] getFields(T t){
     
        return t.getClass().getDeclaredFields();;
    }
    
    //拿到model所有的get方法名字
    public static <T> String[] getMethodsGet(T t){
        Field[] fields = getFields(t);
        //拿到每个属性对应的get方法
        String[] methodNames = new String[fields.length];
        for(int i = 0; i < fields.length; i++){
            methodNames[i] = "get"
                                            + Character.toUpperCase(fields[i].getName().charAt(0))
                                            + fields[i].getName().substring(1);
        }
//System.out.println(Arrays.toString(methodNames));
        return methodNames;
    }
    
    //拿到model中所有的set方法名
    public static <T> String[] getMethodsSet(T t){
        Field[] fields = getFields(t);
        String[] methodNames = new String[fields.length];
        for(int i = 0; i < fields.length; i++){
            methodNames[i] = "set"
                                            + Character.toUpperCase(fields[i].getName().charAt(0))
                                            + fields[i].getName().substring(1);
        }
//System.out.println(Arrays.toString(methodNames));
        return methodNames;
    }
    
    //拿到表名
    public static <T> String getTableName(T t){
        return t.getClass().getName().toLowerCase()
                .substring(t.getClass().getName().toLowerCase().lastIndexOf(".") + 1);
    }
    //通过PreparedStatement往数据库中存入数据
    public static <T> boolean save(PreparedStatement pstmt, T t) throws NoSuchMethodException,
                                                                                                                        SecurityException,
                                                                                                                        IllegalAccessException,
                                                                                                                        IllegalArgumentException,
                                                                                                                        InvocationTargetException,
                                                                                                                        SQLException{
        Field[] fields = getFields(t);
        String[] methodNames = getMethodsGet(t);
        
        for(int i = 1; i < fields.length; i++){
            
                Method m = t.getClass().getMethod(methodNames[i]);
                Class type = m.getReturnType();

//这里通过不同的方法返回值类型使用不同的方法,如果大家的model层中属性的类型都是string类型,可以不用分类,直接setObject()我见过那样的写法,大家可以试试
                if(type.getName().equals("java.lang.String")){
                    pstmt.setString(i, (String) m.invoke(t));
                }else if(type.getName().equals("int")){
                    pstmt.setInt(i, (Integer) m.invoke(t));
                }else if(type.getName().equals("java.sql.Timestamp")){
                    pstmt.setTimestamp(i, (java.sql.Timestamp)m.invoke(t));
                }else if(type.getName().equals("java.util.Date")){
                    pstmt.setDate(i, new java.sql.Date(((java.util.Date) m.invoke(t)).getTime()));
                }
        }
        return true;
    }
    
    public static <T> void load(T t, ResultSet rs) throws SQLException,
                                                                                        NoSuchMethodException,
                                                                                        SecurityException,
                                                                                        IllegalAccessException,
                                                                                        IllegalArgumentException,
                                                                                        InvocationTargetException{
        Field[] fields = getFields(t);
        String[] methodNames = getMethodsSet(t);
        while(rs.next()){
            Method m = null;
            for(int i = 0; i < fields.length; i++){
                Type type = fields[i].getGenericType();
                if(type.toString().equals("int")){
                    m = t.getClass().getMethod(methodNames[i], int.class);
                    m.invoke(t, rs.getInt(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.lang.String")){
                    m = t.getClass().getMethod(methodNames[i], String.class);
                    m.invoke(t, rs.getString(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.sql.Timestamp")){
                    m =t.getClass().getMethod(methodNames[i], java.sql.Timestamp.class);
                    m.invoke(t, rs.getTimestamp(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.util.Date")){
                    m =t.getClass().getMethod(methodNames[i], java.util.Date.class);
                    m.invoke(t, rs.getDate(fields[i].getName().toLowerCase()));
                }
                
            }
        }
    
    }

    public static <T> void list(T t,ResultSet rs,List<T> list) throws NoSuchMethodException,
                                                                                                                SecurityException,
                                                                                                                IllegalAccessException,
                                                                                                                IllegalArgumentException,
                                                                                                                InvocationTargetException,
                                                                                                                SQLException,
                                                                                                                InstantiationException{
        Field[] fields = getFields(t);
        String[] methodNames = getMethodsSet(t);
        Method m = null;
        while(rs.next()){
            t = (T) t.getClass().newInstance();
            
            for(int i = 0; i < fields.length; i++){
                Type type = fields[i].getGenericType();
                if(type.toString().equals("int")){
                    m = t.getClass().getMethod(methodNames[i], int.class);
                    m.invoke(t, rs.getInt(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.lang.String")){
                    m = t.getClass().getMethod(methodNames[i], String.class);
                    m.invoke(t, rs.getString(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.sql.Timestamp")){
                    m =t.getClass().getMethod(methodNames[i], java.sql.Timestamp.class);
                    m.invoke(t, rs.getTimestamp(fields[i].getName().toLowerCase()));
                }else if(type.toString().equals("class java.util.Date")){
                    m =t.getClass().getMethod(methodNames[i], java.util.Date.class);
                    m.invoke(t, rs.getDate(fields[i].getName().toLowerCase()));
                }
            }
            list.add(t);
        }
    }
    
}



3、数据库

package com.zhao.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static Connection getConn(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentsbbs?user=root&password=root");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    
    public static Statement getStmt(Connection conn){
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stmt;
    }
    
    public static PreparedStatement getPStmt(Connection conn, String sql){
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pstmt;
    }
    public static ResultSet getRs(Statement stmt, String sql){
        ResultSet rs = null;
        try {
            stmt.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }
    
    public static void executeUpdate(Statement stmt, String sql) {
        try {
            stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void executeUpdate(Connection conn, String sql){
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        executeUpdate(stmt,sql);
    }
    
    public static ResultSet executeQuery(Connection conn, String sql){
        ResultSet rs = null;
        try {
            rs = conn.prepareStatement(sql).executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }
    public static void close(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn = null;
        }
    }
    
    public static void close(Statement stmt){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            stmt = null;
        }
    }
    
    public static void close(ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            rs = null;
        }
    }
    
    public static int getTotalRecord(ResultSet rs){
        int totalRecord = 0;
        try {
            while(rs.next()){
                totalRecord = rs.getInt(1);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            DB.close(rs);
        }
        return totalRecord;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值