JavaWeb--MVC案例1-------(1)DAO层实现

1.配置c3p0-config.xml

导入包:

 

<c3p0-config>
    <!-- This app is massive! -->
    <named-config name="mvcapp">

        <property name="user">root</property>
        <property name="password">1234</property>
        <property name="driverClass">com.maysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db_person</property>

        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">10</property>
        <property name="maxPoolSize">50</property>

        <!-- intergalactoApp adopts a different approach to configuring statement caching -->
        <property name="maxStatements">20</property>
        <property name="maxStatementsPerConnection">5</property>

    </named-config>
</c3p0-config>

  2.使用dbutils工具包编写DAO((Data Access Object) 数据访问对象是一个面向对象的数据库接口)

 编写jdbcUtils文件,进行数据连接

package MVCCases;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class jdbcUtils {

    public static void release(Connection connection){

        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private static DataSource dataSource = null;//数据源

    static {
        //数据源只能被创建一次
        dataSource = new ComboPooledDataSource("mvcapp");
    }

    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }


}

  

package MVCCases;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

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

public class DAO<T> {

    private QueryRunner queryRunner = new QueryRunner();
    private Class<T> clazz;

    public DAO() {
        clazz = ReflectionUtils.getSuperGenericType(getClass());
    }

    /**
     * 1.Create Retrieve Update Delete
     * INSERT UPDATE DELETE
     */
    public void update(String sql, Object ...args){

        Connection connection = null;

        try{
            connection = jdbcUtils.getConnection();

            queryRunner.update(connection, sql, args);

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 2.查询,返回T的实例的对象
     */
    public T get(String sql, Object ...args){

        Connection connection = null;

        try{

            connection = jdbcUtils.getConnection();
            return queryRunner.query(connection, sql,new BeanHandler<>(clazz), args);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 3.查询,返回T所对应的List<T>
     */
    public List<T> getForList(String sql, Object ...args){

        Connection connection = null;

        try{

            connection = jdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     *4.返回某个字段的值:如返回某一条记录的值,或返回数据表中有多少条记录
     */
    public <E> E getForValue(String sql, Object ...args){

        Connection connection = null;

        try{

            connection = jdbcUtils.getConnection();
            return (E) queryRunner.query(connection, sql,new ScalarHandler(), args);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

  3.编写Customer,和CustomerDAO接口

package MVCCases;

public class Customer {

    private int id;
    private String name;
    private String address;
    private String phone;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Customer(int id, String name, String address, String phone) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    public Customer() {}

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

  CustomerDAO接口

package MVCCases;

import java.util.List;

public interface CustomerDAO {

    public void update(Customer customer);

    public void save(Customer customer);

    public void delete(int id);

    public Customer get(int id);

    public List<Customer> getAll();


}

  4.继承和实现3中的父类和接口

package MVCCases;

import java.util.List;

public class CustomerDAOImpl extends DAO<Customer> implements CustomerDAO {

    @Override
    public void update(Customer customer) {
    }

    @Override
    public void save(Customer customer) {
        String sql = "INSERT INTO customer(name, address, phone) VALUES(?, ?, ?)";
        update(sql, customer.getName(), customer.getAddress(), customer.getPhone());
    }

    @Override
    public void delete(int id) {
        String sql = "DELETE FROM customer WHERE id = ?";
        update(sql, id);
    }

    @Override
    public Customer get(int id) {
        String sql = "SELECT id, name, address, phone FROM customer WHERE id = ?";
        return get(sql, id);
    }

    @Override
    public List<Customer> getAll() {
        String sql = "SELECT id, name, address, phone FROM customer";
        return getForList(sql);

    }
}

  ReflectionUtils

package MVCCases;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ReflectionUtils {

    /**
     * 通过反射获得Class中声明的父类的泛型参数类型
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> Class<T> getSuperGenericType(Class clazz){
        return getSuperGenericType(clazz, 0);
    }

    /**
     * 通过反射,获得定义Class时声明的父类的泛型参数的类型
     * @param clazz
     * @param index
     * @param <T>
     * @return
     */
    public static Class getSuperGenericType(Class clazz, int index) {
        //获得父类泛型类型
        Type genType = clazz.getGenericSuperclass();

        //未被参数化
        if(!(genType instanceof ParameterizedType)){
            return Object.class;
        }

        //当被参数化之后 获取实际的泛型类型参数数组 注意括号
        Type[] params = ((ParameterizedType)genType).getActualTypeArguments();

        if(index >= params.length || index < 0){
            return Object.class;
        }

        if(!(params[index] instanceof Class)){
            return Object.class;
        }
        return (Class)params[index];

    }
}

  

posted @ 2017-12-08 17:50  SkyeAngel  阅读(525)  评论(0编辑  收藏  举报