天天看点

关于Spring访问数据层的几个方法,从spring-jdbc到jdbctemplate到hibernatetemplate

代码结构

关于Spring访问数据层的几个方法,从spring-jdbc到jdbctemplate到hibernatetemplate

引入代码

从入口开始

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

import spring_jdbc.dao.CustomerDAO;
import spring_jdbc.model.Customer;

public class App {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
        CustomerDAO customerDao = (CustomerDAO) context.getBean("customerDAO");
        Customer customer = new Customer(, "can", );
        customerDao.insert(customer);

        Customer findCustomer = customerDao.findByCustomerId();
        System.out.println(findCustomer.getId());
        System.out.println(findCustomer.getName());
        System.out.println(findCustomer.getAge());
    }
}
           

想看源码的时候遇到问题,ctrl 不能attach source,解决方案

设置java反编译工具

程序解释:

ApplicationContext的中文意思是“应用前后关系”,它继承自BeanFactory接口,代表一个上下文的环境,具体介绍见

ApplicationContext

Spring-Module.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <import resource="database/Spring-Datasource.xml" />
    <import resource="customer/Spring-Customer.xml" />

</beans>
           

关于xmlns

Spring-Datasource.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

</beans>
           

Spring.customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="customerDAO" class="org.thinkingingis.dao.impl.JdbcCustomerDAO">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>
           

Customer类

package spring_jdbc.model;

//创建一个与customer表对应的实体类,以便存放 Customer对象

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

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

    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 int getAge() {
        return age;
    }

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

CustomerDao

package spring_jdbc.dao;

import spring_jdbc.model.Customer;

public interface CustomerDAO {
    public void insert(Customer customer);
    public Customer findByCustomerId(int custId);
}
           

JdbcCustomerDAO implements CustomerDAO

package spring_jdbc.dao.impl;

import spring_jdbc.dao.CustomerDAO;
import spring_jdbc.model.Customer;

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

import javax.sql.DataSource;

public class JdbcCustomerDAO implements CustomerDAO {

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


    public void insert(Customer customer) {

        String sql = "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
        Connection conn = null;

        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(, customer.getId());
            ps.setString(, customer.getName());
            ps.setInt(, customer.getAge());
            ps.executeUpdate();
            ps.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            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(, custId);
            Customer customer = null;
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                customer = new Customer(
                        rs.getInt("CUST_ID"), 
                        rs.getString("NAME"), 
                        rs.getInt("age")
                );
            }
            rs.close();
            ps.close();
            return customer;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {

                    e.printStackTrace();
                }
            }
        }


    }

}
           

程序解释:

datasource简单解释

配置datasource的三种方法

什么是JNDI

关于preparedstatement

整合xml,注入,注释添加请看下集