37 Spring+JDBC实例

作者: 笑Skr人啊 | 来源:发表于2017-08-25 15:18 被阅读15次

1. Customer 表

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;

2. Customer模型

添加一个客户模型用来存储用户的数据。

package com.gp6.jdbc.bean;

public class Customer {
    private int custId;
    private String name;
    private int age;
    
    public Customer(int custId, String name, int age) {
        this.custId = custId;
        this.name = name;
        this.age = age;
    }
    
    
    public int getCustId() {
        return custId;
    }
    public void setCustId(int custId) {
        this.custId = custId;
    }
    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;
    }
}

3. 数据访问对象 (DAO) 模式

package com.gp6.jdbc.dao;

import com.gp6.jdbc.bean.Customer;

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

客户的DAO实现,使用 JDBC 发出简单的 insert 和 select SQL语句。

package com.gp6.jdbc.dao.impl;

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

import javax.sql.DataSource;

import com.gp6.jdbc.bean.Customer;
import com.gp6.jdbc.dao.CustomerDAO;

public class CustomerDAOImpl 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(1, customer.getCustId());
            ps.setString(2, customer.getName());
            ps.setInt(3, customer.getAge());
            ps.executeUpdate();
            ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {}
            }
        }
    }
    
    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.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) {}
            }
        }
    }
}

4. Spring bean配置

创建 customerDAO 和数据源在 Spring bean 配置文件中。
File : 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-2.5.xsd">

    <bean id="customerDAO" class="com.gp6.jdbc.dao.impl.CustomerDAOImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

File : Spring-Datasource.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-2.5.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/study" /> 
        <property name="username" value="root" /> 
        <property name="password" value="123456" />
    </bean>

</beans>

File : application.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-2.5.xsd">

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

</beans>

5.项目结构

本实例完整目录结构。

Paste_Image.png

6.运行它

package com.gp6.jdbc;

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

import com.gp6.jdbc.bean.Customer;
import com.gp6.jdbc.dao.CustomerDAO;

public class Test {
    public static void main( String[] args ) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/gp6/jdbc/etc/applicationContext.xml");
         
        CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
        Customer customer = new Customer(1, "gp6",23);
        customerDAO.insert(customer);
        
        Customer customer1 = customerDAO.findByCustomerId(1);
        System.out.println(customer1);
        
    }
}   


运行可能会报如下错误

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in class path resource [com/gp6/jdbc/etc/Spring-Datasource.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1262)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1331)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:897)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:566)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.gp6.jdbc.Test.main(Test.java:11)
Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:417)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1283)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1254)
    ... 9 more

是因为缺少jar包的缘故

将下面两个jar包引入

spring-jdbc-3.2.8.RELEASE
mysql-connector-java-5.1.29

相关文章

  • 37 Spring+JDBC实例

    1. Customer 表 2. Customer模型 添加一个客户模型用来存储用户的数据。 3. 数据访问对象 ...

  • Spring+JDBC实例

    Customer 表 在这个例子中,我们使用的是MySQL数据库。CREATE TABLE customer (C...

  • Python 练习实例37

    来自菜鸟教程https://www.runoob.com/python/python-exercise-examp...

  • python零基础入门到实战,基础知识总结(二)

    33 类 34 类 汽车里程表 35 子类方法 init () 36 class实例 37 文件和异常 38 将数...

  • 菜鸟编程学习(python&C--018)

    Python 练习实例37 Python 100例 题目:对10个数进行排序。 程序分析:可以利用选择法,即从后...

  • 《Effective Objective-C 2.0编写高质量i

    37. 理解 “块” 这一概念 实例: 全局块、栈块及堆块 要点总结 块(block)是C、OC、C++中的词法闭...

  • 37

    计算 37×3 37×6 37×9 37×12 37×15 37×18 37×21 37×24 37×27

  • 使用Spring+JDBC访问数据库

    JDBC是允许用户在不同数据库之间做选择的一个抽象层。JDBC允许开发者用JAVA写数据库应用程序,而不需要关心底...

  • 9_智能指针示例

    智能指针在37_智能指针分析中详细学习过。此处实例中通过模板实现了可复用的智能指针模板类 需要一个特殊的指针——通...

  • 37秒

    37年,仿佛37秒

网友评论

    本文标题:37 Spring+JDBC实例

    本文链接:https://www.haomeiwen.com/subject/yywudxtx.html