JDBC evolution 4-Final evolution, JDBC evolution 4-Evolution

Source: Internet
Author: User

JDBC evolution 4-Final evolution, JDBC evolution 4-Evolution

Apart from directly calling the jar package provided by the open-source organization, what I want to talk about today is the final version of JDBC, which requires us to practice more and understand more. The most important thing is understanding. Let's get started.
In the morning, I sorted the contents of yesterday and wrote the common methods for processing transactions into the JDBCUtils tool class.
In fact, all the detailed code has been implemented here. The next step is to integrate and control the content as a whole.
DAO:
Now we want this program to be more automated. We only need to provide a connection to return an object, an object set, or a result to us. Or we provide a connection and an object, which can automatically implement addition, deletion, and modification. Then DAO is generated in this way.
In the Application generic class, we design DAO as a parent class suitable for adding, deleting, modifying, and querying different objects. Specific operations are completed by manipulating the sub-classes DAO of a specific object class.
Let's look at the Code:
DAO:

public class Dao<T> {    Class<T> clazz = null;    @SuppressWarnings("unchecked")    public Dao(){        Type type = this.getClass().getGenericSuperclass();        ParameterizedType pt = (ParameterizedType) type;        Type[] types = pt.getActualTypeArguments();        clazz = (Class<T>) types[0];        System.out.println(clazz);    }    protected List<T> getGroupValue(Connection conn, String sql, Object...args){        List<T> list = new ArrayList<T>();        // get PreparedStatement's object        PreparedStatement ps = null;        // execute sql        ResultSet rs = null;        try {            ps = conn.prepareStatement(sql);            // set ps            for(int i = 0; i < args.length; i++){                ps.setObject(i+1, args[i]);            }            rs = ps.executeQuery();            ResultSetMetaData rsmd = rs.getMetaData();            int columnCount = rsmd.getColumnCount();            System.out.println(columnCount);            while(rs.next()){                T t = clazz.newInstance();                for(int i = 1; i <= columnCount; i++){                    // read                    String columnName = rsmd.getColumnLabel(i);                    Object columnValue = rs.getObject(columnName);                    // write                    Field field = clazz.getDeclaredField(columnName);                    field.setAccessible(true);                    field.set(t, columnValue);                }                list.add(t);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            JDBCUtils.close(rs, ps, null);        }        return list;    }    protected Object getValue(Connection conn, String sql, Object... args){        Object object = null;        PreparedStatement ps = null;        ResultSet rs = null;        try {            // get PreparedStatement's object            ps = conn.prepareStatement(sql);            // set ps             for(int i = 0; i < args.length; i++){                ps.setObject(i+1, args[i]);            }            // execute the sql            rs = ps.executeQuery();            // read rs            if(rs.next()){                object = rs.getObject(1);            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            JDBCUtils.close(rs, ps, null);        }        return object;    }    /**     * getPrepareAllTransaction()     *      * @param conn     * @param sql     * @param clazz     * @param args     * @return     */    protected List<T> getPrepareAllTransaction(Connection conn, String sql,            Object... args) {        List<T> list = new ArrayList<T>();        // get PreparedStatement        PreparedStatement ps = null;        // execute the sql        ResultSet rs = null;        try {            ps = conn.prepareStatement(sql);            // set the ps            for (int i = 0; i < args.length; i++) {                ps.setObject(i + 1, args[i]);            }            rs = ps.executeQuery();            // get the columnNum            ResultSetMetaData rsmd = rs.getMetaData();            int columnNum = rsmd.getColumnCount();            // read the rs and write to an object            while (rs.next()) {                T t = clazz.newInstance();                for (int i = 1; i <= columnNum; i++) {                    // read                    String columnName = rsmd.getColumnLabel(i);                    Object columnVal = rs.getObject(columnName);                    // through the method(reflect)                    PropertyUtils.setProperty(t, columnName, columnVal);                }                list.add(t);            }        } catch (Exception e) {            e.printStackTrace();        } finally {            JDBCUtils.close(rs, ps, null);        }        return list;    }    /**     * getTransacation     *      * @param conn     * @param sql     * @param clazz     * @param args     * @return     */    protected T getPrepareTransaction(Connection conn, String sql, Object... args) {        T t = null;        // get PreparedStatement's object        PreparedStatement ps = null;        ResultSet rs = null;        try {            ps = conn.prepareStatement(sql);            // set the ps            ps.setObject(1, args[0]);            rs = ps.executeQuery();            ResultSetMetaData rsmd = rs.getMetaData();            int columnNum = rsmd.getColumnCount();            // read and write            if (rs.next()) {                t = clazz.newInstance();                for (int i = 1; i <= columnNum; i++) {                    // read                    String columnName = rsmd.getColumnLabel(i);                    Object columnValue = rs.getObject(columnName);                    // write                    Field field = clazz.getDeclaredField(columnName);                    field.setAccessible(true);                    field.set(t, columnValue);                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            JDBCUtils.close(rs, ps, null);        }        return t;    }    /**     * Update     *      * @param conn     * @param sql     * @param args     * @return     */    protected int transactionUpdate(Connection conn, String sql, Object... args) {        // get preparedStatement's object        PreparedStatement ps = null;        // execute the ps        int rows = 0;        try {            conn = JDBCUtils.getConnection();            ps = conn.prepareStatement(sql);            for (int i = 0; i < args.length; i++) {                ps.setObject(i + 1, args[i]);            }            rows = ps.executeUpdate();        } catch (Exception e) {            e.printStackTrace();        } finally {            JDBCUtils.close(ps, null);        }        // return        return rows;    }}

It is found that the method in it is no different from the method we wrote earlier, but because T is declared in DAO, we do not need to declare it again in the method below. A constructor is provided to obtain the generic type of the parent class of the current object using reflection.this.getClass().getGenericSuperClass();This is to obtain all the generic types of the parent class, which may have a value suchDAO<T>, There may also be multiple values, suchMap<K, V>Through the API, we found that there is no such method in the Type to retrieve all the types in it, and its subinterface provides this method.
ParameterizedType pt = (ParameterizedType) type;
getActualTypeArguments()Returns an array of type. Here, we know that there is a generic type, and the element directly indexed to 0 is a generic type.

Create a specific operation class:

public class UserDAO extends Dao<User>{    // select function    public Object getSpecialValue(Connection conn){        String sql = "SELECT count(*) FROM users";        return getValue(conn, sql);    }    // select All    public List<User> getAllUser(Connection conn){        String sql = "SELECT * FROM users";        return getPrepareAllTransaction(conn, sql);    }    // select info through id....    public User getUser(Connection conn, int id){        String sql = "SELECT * FROM users WHERE id = ?";        return getPrepareTransaction(conn, sql, id);    }    //delete    public int delete(Connection conn, int id){        String sql = "DELETE FROM users WHERE id = ?";        return transactionUpdate(conn, sql, id);    // update    public int update(Connection conn, User user){        String sql = "UPDATE users SET address = ? WHERE id = ?";        return transactionUpdate(conn, sql, user.getAddress(), user.getId());    }    // insert    @Test    public int insert(Connection conn, User user){        String sql = "INSERT INTO users(name, address, phone) values(?,?,?)";        int rows = transactionUpdate(conn, sql, user.getName(), user.getAddress(), user.getPhone());        return rows;    }}

This class is used to operate the User class. The test will not be written here. Let's talk about the new constructor.
When we create UserDao, it will call the parameter-free constructor of UserDao by default, and because of inheritance, the UserDao constructor calls the DAO constructor of the parent class by default, and analyzes the constructor according to the above steps.
The advantage of this is that we do not need to repeatedly write the Class clazz parameter in some methods.
Even if DAO is finished.
So far, we have to draw a split line. We need to understand more about the previous sections. This is the basis and core of the three major learning frameworks. Write it three times from evolution 1 to final evolution in an editor. I feel necessary.

---------------- Gorgeous split line --------------
The following are some tool classes provided by the open-source organization, which can help us complete all the above content. Of course they may write better, but the core idea is above.

Get connection:
Recommendation: c3p0
Recommended reason: You can configure it using an xml file.

Execute the SQL statement:
DbUtils ()

For more information, see the help documentation.

Today, I am so sleepy that my school has a lot of troubles. I wanted to give up on this blog. But I thought again. If I give up, it will give me more reasons to give up later, and I will overcome it. I will stick to it. Come on, young man.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.