学习Spring第二天

Author Avatar
人不如故 10月 20, 2017
  • 在其它设备中阅读本文章

在Spring中使用jdbc


添加gradle依赖

dependencies {

testCompile group: 'junit', name: 'junit', version: '4.12'

compile group: 'org.springframework', name: 'spring-context', version: '5.0.0.RELEASE'

compile group: 'org.springframework', name: 'spring-jdbc', version: '5.0.0.RELEASE'

compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.8-dmr'

}

首先创建数据表

CREATE TABLE `customer` (
    `CUST_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `NAME` varchar(100) NOT NULL,
    `AGE` int(10) unsigned NOT NULL,
        PRIMARY KEY (`CUST_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

下面实现业务代码

创建一个Customer实体类

package com.demo.Model;

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

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

    public int getCusId() {
        return cusId;
    }

    public void setCusId(int cusId) {
        this.cusId = cusId;
    }

    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;
    }

    @Override
    public String toString() {
        return "id: " + cusId + "\nname: " + name + "\nage: " + age;
    }
}

下面创建一个DAO

public interface CustomerDao {
    void insert(Customer customer);

    Customer findByCustomerId(int cusId);
}

创建一个DAO的实现层

public class JdbcCustomerDao implements CustomerDao {
    private DataSource dataSource;

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

    @Override
    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(1, customer.getCusId());
            ps.setString(2, customer.getName());
            ps.setInt(3, customer.getAge());
            ps.executeUpdate();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这里采用最原始的jdbc对数据库进行操作,通过dataSource的方式获取connection.dataSource通过Spring-DataSource.xml获取

下面创建Spring-Dataource.xml

<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.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/Spring"/>
        <property name="username" value="root"/>
        <property name="password" value="19970819wy"/>
    </bean>
</beans>

这里使用Spring-JDBC,配置好jdbc的一系列信息

Spring-Customer.xml

<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="com.demo.DaoImpl.JdbcCustomerDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Spring-Moudle.xml

<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="Spring-DataSource.xml"/>
    <import resource="Spring-Customer.xml"/>
</beans>

到此为止xml配置文件已经写完了,最后写个测试类测试一下

App.java

package com.demo;

import com.demo.Dao.CustomerDao;
import com.demo.Model.Customer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

        CustomerDao customerDAO = (CustomerDao) context.getBean("customerDAO");
        Customer customer = new Customer(1, "RenBuRuGu",20);
        customerDAO.insert(customer);

        Customer customer1 = customerDAO.findByCustomerId(1);
        System.out.println(customer1);

    }
}

运行结果如下:

坚持原创技术分享,您的支持将鼓励我继续创作!