Spring JDBC-Beispiel

Spring + JDBC-Beispiel

In diesem Tutorial erweitern wir die letztenMaven + Spring hello world example durch Hinzufügen von JDBC-Unterstützung, um mit Spring + JDBC einen Datensatz in eine Kundentabelle einzufügen.

1. Kundentabelle

In diesem Beispiel verwenden wir eine MySQL-Datenbank.

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=2 DEFAULT CHARSET=utf8;

2. Projektabhängigkeit

Fügen Sie Spring- und MySQL-Abhängigkeiten in die Datei von Mavenpom.xmlein.

Datei: pom.xml


  4.0.0
  com.example.common
  SpringExample
  jar
  1.0-SNAPSHOT
  SpringExample
  http://maven.apache.org

  

        
    
        org.springframework
        spring
        2.5.6
    

        
    
        mysql
        mysql-connector-java
        5.1.9
    

  

3. Kundenmodell

Fügen Sie ein Kundenmodell hinzu, um Kundendaten zu speichern.

package com.example.customer.model;

import java.sql.Timestamp;

public class Customer
{
    int custId;
    String name;
    int age;
    //getter and setter methods

}

4. DAO-Muster (Data Access Object)

Kunden-Dao-Schnittstelle.

package com.example.customer.dao;

import com.example.customer.model.Customer;

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

Bei der Implementierung von Customer Dao können Sie mithilfe von JDBC eine einfache Anweisung zum Einfügen und Auswählen ausgeben.

package com.example.customer.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.example.customer.dao.CustomerDAO;
import com.example.customer.model.Customer;

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(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) {}
            }
        }
    }
}

5. Spring Bean Konfiguration

Erstellen Sie die Spring Bean-Konfigurationsdatei für customerDAO und die Datenquelle.
File : Spring-Customer.xml



    
        
    

Datei: Spring-Datasource.xml



    

        
        
        
        
    

Datei: Spring-Module.xml



    
    

6. Projektstruktur überprüfen

Vollständige Verzeichnisstruktur dieses Beispiels.

image

7. Starte es

package com.example.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.customer.dao.CustomerDAO;
import com.example.customer.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(1, "example",28);
        customerDAO.insert(customer);

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

    }
}

Ausgabe

Customer [age=28, custId=1, name=example]

Quellcode herunterladen

Laden Sie es herunter -SpringJDBCExample.zip (10 KB)