Spring Learning (nine) Spring and database programming

This article reference: the Spring Learning

First, the traditional JDBC Review

With a big brother to simply look at the demo

/ ** 
 * Use jdbc, according to information query id of a single Student 
 * / 
public  class JdbcManage {
     public Student getOneStudent ( int id) { 

        String SQL = "the SELECT id, name the FROM Student the WHERE id =?" ; 
        Student Student = null ;
         / / declare variables JDBC 
        Connection CON = null ; 
        PreparedStatement PS = null ; // role: precompiled sql command 
        ResultSet rs = null ; // query result sets returned by the database 
        the try {
             // Register driver
            The Class.forName ( "com.myql.jdbc.Driver" );
             // get a connection 
            con = DriverManager.getConnection ( "jdbc: // mysql: // localhost:" + "3306 / student", "root", "root " );
             // precompiled the SQL 
            PS = con.prepareStatement (SQL);
             // set parameters 
            ps.setInt (. 1 , ID);
             // execute the SQL 
            RS = ps.executeQuery ();
             // assembled result set returned POJOs 
            IF (rs.next ()) { 
                Student = new new Student (); 
                student.setId (RS.getInt ( 1 ));
                student.setName(rs.getString(1));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接资源
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (ps != null && !ps.isClosed()) {
                    ps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (con != null && con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return student;
    }
}

Second, the optimization of the traditional JDBC

Step 1: Create DBUtil class

The first step we can repeat the template code is proposed to create a database [Tools] DBUtil

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    static String ip = "127.0.0.1";
    static int port = 3306;
    static String database = "student";
    static String encoding = "UTF-8";
    static String loginName = "root";
    static String password = "root";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
        return DriverManager.getConnection(url, loginName, password);
    }
}

Step 2: Use try-catch statement automatically shut resources

  PS: Auto-shutdown is intrinsic JDK 7 (try-with-resources) newly introduced

  PS: use: try keyword followed by a pair of parentheses, parentheses can declare, initialize one or more resources, here it refers to the resources that must be closed at the end of the program resources, try statement in the statement automatically shut down at the end of these resources.

public Student getOne ( int the above mentioned id) { 

    String SQL = "the SELECT the above mentioned id, name the FROM Student the WHERE the above mentioned id =?" ; 
    Student Student = null ;
     // PS: The JDBC declare variables included in the try (..) will automatically shut down in the resource 
    try (Connection DBUtil.getConnection = CON (); the PreparedStatement PS = con.prepareStatement (SQL)) { 

        // set parameters 
        ps.setInt (. 1 , ID);
         // execute the SQL 
        the ResultSet RS = ps.executeQuery ();
         // assembly result set is returned POJOs 
        IF (rs.next ()) { 
            Student = new new Student ();
            student.setId(rs.getInt(1));
            student.setName(rs.getString(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return student;
}

The third step: further improvement class DBUtil

  Add a method DBUtil class used to directly return a result set:

 / ** 
     * General Query db 
     * @param SQL statement SQL 
     * @param parameter objects sql statement 
     * @return 
     * @throws SQLException
      * / 
    public  static the ResultSet the getResultSet (SQL String, Object [] Objects) throws SQLException { 

        the ResultSet RS = null ;
         the try (CON = Connection the getConnection (); the PreparedStatement PS = con.prepareStatement (SQL)) { 

            // the parameters passed in, provided SQL placeholder value 
            for ( int I = 0; I <objects.length; I ++ ) {
                // loop here may be seen as a result set corresponding to each ID stored thing is a sql query result set out 
                ps.setObject (I +. 1 , Objects [I]); 
            } 
            // execute SQL statements and accept result set 
            RS = ps.executeQuery (); 
        } 
        // return result sets 
        return RS; 
    }

  The final code:

public Student getOne(int id) throws SQLException {

    String sql = "SELECT id,name FROM student WHERE id = ?";
    Object[] objects = {id};
    Student student = null;
    try (ResultSet rs = DBUtil.getResultSet(sql, objects);) {
        student.setId(rs.getInt(1));
        student.setName(rs.getString(1));
    }
    return student;
}

Three, the Spring of JDBC

  To use Spring JDBC in the module, it is necessary to introduce the appropriate jar file:

  • We need to introduce the jar package:
  • spring-jdbc-4.3.16.RELEASE.jar
  • spring-tx-4.3.16.RELEASE.jar

  Fortunately, in the creation of Spring IDEA project has been automatically deployed for us, then we have to actually use it in Spring JDBC

Metabase Explorer

  As we create DBUtil class, which will be connected to the information package on the inside, as here, only a brief Jdbc Template manner.

Jdbc Template

  Spring provides a Jdbc Template class that they have a DataSource encapsulates the type of a variable, we can directly use:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置数据源-->
    <bean id="dataSrouce" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/student"/>
    </bean>
    <!--配置扫描的包-->
    <context:component-scan base-package="jdbc"/> 
    <! - with jdbcTemplate Spring to configure with just a data source, let the program call -> 
    < bean the above mentioned id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" > 
        < Property name = "the dataSource" REF = "dataSrouce" /> 
    </ the bean > 
</ Beans >

  Redrafting class JDBC operations:

package jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import pojo.Student;

import java.sql.ResultSet;
import java.sql.SQLException;

@Component("jdbc")
public class JDBCtest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询单条数据
     *
     * @param stuID
     * @return
     * @throws SQLException
     */
    public Student getOne(int stuID) throws SQLException {

        String sql = "SELECT id, name FROM student WHERE id = ?";
        Student student = jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student stu = new Student();
                stu.setId(resultSet.getInt("id")); 
                Stu.setName (resultSet.getString ( "name" ));
                 return STU; 
            } 
        }, 123456789 );
         return Student; 
    } 

    / ** 
     * add a data 
     * 
     * @param Student
      * / 
    public  void the Add (Student Student ) {
         the this .jdbcTemplate.update ( "the INSERT the INTO Student (ID, name) the VALUES (,??)" , 
                student.getId (), student.getName ()); 
    } 

    / ** 
     * update a data 
     * 
     * @param student
     */
    public void update(Student student) {
        this.jdbcTemplate.update("UPDATE student SET name = ? WHERE id = ?",
                student.getName(), student.getId());
    }

    /**
     * 删除一条数据
     *
     * @param id
     */
    public void delete(int id) {
        this.jdbcTemplate.update("DELETE FROM student WHERE id = ?",
                id);
    }
}

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/riches/p/11572396.html