Spring原生JDBC使用

7757 ワード

Spring原生JDBC使用
Springデカップリングの理解を深めるため,今回の実験学習ではSpringでJDBCを接続する
一、POMプロファイル
pom.xml

    4.0.0

    fanghao
    myspring
    1.0-SNAPSHOT
    jar

    myspring
    http://maven.apache.org

    
        UTF-8
    

    
        
            junit
            junit
            3.8.1
            test
        

        
        
            org.springframework
            spring-context
            5.0.5.RELEASE
        

        
        
            mysql
            mysql-connector-java
            8.0.9-rc
        

        
            org.springframework
            spring-jdbc
            5.0.5.RELEASE
        

    


二、ユーザークラス
Customer.java
package newHello.customer;


public class Customer {
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;

    }

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


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

三、ユーザーDAOインタフェース
CustomerDAO.java
package newHello.customer;

/**
 * DAO(Data Access Object)      
 */
public interface CustomerDAO {
    void insert(Customer customer);

    Customer findByCustomerId(int custId);
}

四、ユーザーDAOインタフェース実装クラス
package newHello.customer;

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

public class JdbcCustomerDAO implements CustomerDAO {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     *   prepareStatement  SQL
     * @param customer          
     */
    public void insert(Customer customer) {
        String sql = "insert into CUSTOMER " +
                "(NAME, AGE) VALUES(?, ?)";
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, customer.getName());
            ps.setInt(2, customer.getAge());
            ps.executeUpdate();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }

    public Customer findByCustomerId(int custId) {
        String sql = "select * from CUSTOMER where CUST_ID = ?";
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, custId);
            Customer customer = null;
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                customer = new Customer(
                        rs.getString("NAME"),
                        rs.getInt("Age")
                );
            }
            rs.close();
            ps.close();
            return customer;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

五、資源ファイル
リソースファイルは主に構成され、java beanを管理します.
➜  resources tree .
.
├── Spring-Customer.xml
├── Spring-Datasource.xml
└── Spring-Module.xml

0 directories, 3 files

5.1 Spring-Customer.xml


    
    
        
    

5.2 Spring-Datasource.xml


    
    

        
        
        
        
    


5.3 Spring-Module.xml


    
    
    

六、アプリケーション起動プログラム
App.java
package newHello.customer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        //   XML           
        ApplicationContext context =
                new ClassPathXmlApplicationContext("Spring-Module.xml");


        //   customerDAO JavaBean,   customerDAO
        CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

        //     DAO    ORM   
        customerDAO.insert(new Customer("Jack", 21));
        customerDAO.insert(new Customer("Tom", 24));
        customerDAO.insert(new Customer("Jane", 25));

        Customer customer = customerDAO.findByCustomerId(2);
        System.out.println(customer);
    }
}

七、運行結果
Customer{name=Tom, age=24}

転載先:https://www.cnblogs.com/fanghao/p/8764976.html