MVC案例的實現


要求一:加入C3P0數據源

——C3P0

——數據庫驅動的jar包

1.首先在src目錄下創建c3p0的配置文件c3p0-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config>
        <!--連接池在無空閑連接可用時一次性創建的新數據庫連接數,default:3-->
        <property name="acquireIncrement">5</property>
        <!--連接池初始化時創建的連接數,default:3-->
        <property name="initialPoolSize">10</property>
        <!--連接池保持的最小連接數,default:3-->
        <property name="minPoolSize">10</property>
        <!--連接池中擁有的最大連接數,如果獲得新連接時,
        連接總數超過這個值則不會再獲取新連接,而是等待其他連接釋放-->
        <property name="maxPoolSize">50</property>
        <!--連接池為數據源緩存的preparedstatement的總數-->
        <property name="maxStatements">20</property>
        <!--連接池為數據源單個connection緩存的preparedstatement數-->
        <property name="maxStatementsPerConnection">5</property>

    </default-config>
    <named-config name="mysql">
        <property name="user">root</property>
        <property name="password">password</property>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/yang</property>

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

</c3p0-config>

  

2.創建一個JdbcUtil類,創建一個c3p0連接池,並且創建連接,銷毀連接。

public class JdbcUtils {
    /**
     * 釋放Connection連接
     * @param connection
     */
    public static void releaseConnection(Connection connection){

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

    }

    private static DataSource dataSource = null;

    static{
        dataSource = new ComboPooledDataSource("mysql");
    }

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

 

3.可以創建一個測試類來測試,第一個測試是否可以獲取一個連接。

  @Test
    public void testGetConnection() throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        System.out.println(connection);
    }

  

要求二:編寫DAO、DBUtils工具欄和CustomerDAO接口

提供CustomerDAO接口的實現類:CustomerDAOImpl

 

1.實體類:

package com.mvcapp.entity;

import java.io.Serializable;

public class Customer implements Serializable {
    private Integer id;
    private String name;
    private String password;

    public Customer(Integer id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public Customer(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public Customer() {
    }

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

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

  

2.DAO

package com.mvcapp.dao;

import com.mvcapp.db.JdbcUtils;
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.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

/**
 * 封裝了基本的CRUD的方法,以供子類繼承使用
 * 當前DAO直接在方法中獲取數據庫連接
 * 整個DAO采取DBUtils解決方案
 * @param <T>:當前DAO處理的實體類的類型是什么?
 *
 */
public class DAO<T> {

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

    public DAO(){
        //獲得運行時類的超類的類型
        Type superClass = getClass().getGenericSuperclass();

        if (superClass instanceof ParameterizedType){
            ParameterizedType parameterizedType = (ParameterizedType) superClass;

            Type [] typeArgs = parameterizedType.getActualTypeArguments();
            if (typeArgs !=null && typeArgs.length >0){
                if (typeArgs[0] instanceof Class ){
                    clazz = (Class<T>) typeArgs[0];
                }
            }
        }
    }
    
    /**
     * 獲取一條記錄
     * @param sql
     * @param args
     * @return
     */
    public T get(String sql,Object ...args){
        Connection connection = null;

        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection,sql,new BeanHandler<>(clazz),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.releaseConnection(connection);
        }
        return null;
    }

    /**
     * 獲取一組值
     * @param sql
     * @param args
     * @return
     */
    public List<T> getForList(String sql,Object ...args){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection,sql,new BeanListHandler<>(clazz));
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.releaseConnection(connection);
        }
        return  null;
    }

    /**
     * 返回某一個字段的值,例如返回某一條記錄的customerName,或返回數據表中國有多少條記錄
     * @param sql
     * @param args
     * @param <E>
     * @return
     */
    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 (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.releaseConnection(connection);
        }
        return  null;
    }
    /**
     * 該方法封裝了INSERT、DELETE、UPDATE操作
     * @param sql:SQL語句
     * @param args:填充SQL語句的占位符
     */
    public void update(String sql,Object ...args){
        Connection connection = null;

        try {
            connection = JdbcUtils.getConnection();
            queryRunner.update(connection,sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.releaseConnection(connection);
        }
    }
}

  

3.CustomerDAO接口

package com.mvcapp.dao;

import com.mvcapp.entity.Customer;

import java.util.List;

public interface CustomerDAO {
    public List<Customer> getAll();

    public void save(Customer customer);

    public Customer get(Integer id);

    public void delete(Integer id);

    /**
     * 返回和name相等的記錄
     * @param name
     * @return
     */
    public long getCountWithName(String name);
}

  

4.CustomerDAOImpl實現類:

package com.mvcapp.daoimpl;

import com.mvcapp.dao.CustomerDAO;
import com.mvcapp.dao.DAO;
import com.mvcapp.entity.Customer;

import java.util.List;

public class CustomerDAOImpl extends DAO<Customer> implements CustomerDAO {
    @Override
    public List<Customer> getAll() {
        String sql = "SELECT * FROM CUSTOMER";
        return getForList(sql);
    }

    @Override
    public void save(Customer customer) {
        String sql = "insert into customer(name,password) values(?,?)";
        update(sql,customer.getName(),customer.getPassword());
    }

    @Override
    public Customer get(Integer id) {
        String sql = "select * from customer where id=?";
        return get(sql,id);
    }

    @Override
    public void delete(Integer id) {
        String sql ="delete from customer where id=?";
        update(sql,id);
    }

    @Override
    public long getCountWithName(String name) {
        String sql = "Select count(id) from customer where name=?";
        return getForValue(sql,name);
    }
}

  

5.CustomerDAOImplTest測試類:

package com.mvcapp.test;

import com.mvcapp.dao.CustomerDAO;
import com.mvcapp.daoimpl.CustomerDAOImpl;
import com.mvcapp.entity.Customer;
import org.junit.jupiter.api.Test;

import java.util.List;

public class CustomerDAOImplTest {
    private CustomerDAO customerDAO = new CustomerDAOImpl();
    @Test
    public void testGet(){
       Customer customer =  customerDAO.get(1);
        System.out.println(customer);
    }

    @Test
    public void testSave(){
        Customer customer = new Customer("Wang","222");
        customerDAO.save(customer);
    }

    @Test
    public void testdelete(){
        int id = 4;
        customerDAO.delete(id);
    }

    @Test
    public void testlist(){
        List<Customer> list = customerDAO.getAll();
        System.out.println(list);
    }

    @Test
    public void testcount(){
        long i = customerDAO.getCountWithName("SEN");
        System.out.println(i);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM