Spring JdbcTemplate Source Reading report

Source: Internet
Author: User
Tags class definition

    • Write in front

Spring has always been shanfanjiujian, so we have designed a very popular bean management model that simplifies the management of beans in development and writes a lot less repetitive code. JdbcTemplate's design is more impressive, lightweight, and can be used as an ORM as well as a JDBC-like flexibility. And in JdbcTemplate a class, contains two kinds of design patterns, read after the benefit, today is summarized.

    • Design Pattern Basics

If hard to read, then go to the fur of the kidnap of a blog, the first design pattern familiar, understand its structure, and then to read, not only to improve the understanding.

The two design patterns contained in JdbcTemplate are: Process control mode, callback mode .

The so-called process Control, is defined by the parent class A method, the method contains a number of processes, the fixed process of privatization, in which the subclass cannot be overridden by the privatization method; If the process is implemented by default, the subclass can choose to implement, if the process is abstracted, deferred to the subclass to implement, that is, the custom implementation, Present the code.

    For example: Boiled beef, must be cut first, salted (necessary process) Hot pot oil (default implementation) Stir fry (custom process)

 Public Abstract classfather{//Process M1->M2->M3     Public Final voidTemplatemethod (Statementcallback statementcallback) {method1 ();        Method2 (); //the subclass of abstract methods is responsible for implementing the usual businessStatementcallback.method3 ();//provided by the interface    }    //Parent class Private methods cannot override Process Control    Private voidmethod1 () {System.out.println ("Father private method, control by Father"); }    //The hook method enables the parent class to provide a default implementation     Public voidmethod2 () {System.out.println ("Default method,prevent by Father"); }}

such as the above class, clear process model, based on the implementation of METHOD2 customization. What are the benefits of this design pattern?

When we first learned JDBC, the most common code was.

String driver= "Com.mysql.jdbc.Driver";      Connection con; String URL= "Jdbc:mysql://localhost:3306/demo"; String User= "Root"; String pwd= "12345"; //connect the database MySQL     Public voidConnection2mysql () {Try{class.forname (driver); Con=drivermanager.getconnection (URL,USER,PWD); if(!con.isclosed ()) System.out.println ("Connection succeeded"); } Catch(Exception e) {e.printstacktrace (); }            }

After the repeated writing process, the designer realizes that this effort to slow down the efficiency, must use a design pattern to let the programmer pay more attention to more valuable things, so this fixed process is included in the process of the parent class definition, and can not be modified within the scope.

The second design mode, callback mode.

Callbacks are ubiquitous in the modern internet, which is one of the benefits of polymorphism that can be customized as needed, such as

$ ("#button"). Click (function() {    //logic});

This callback pattern, which is popular in programming, is an asynchronous callback model if you add async. The reason for its popularity is customization. In Java, the build callback pattern only needs to define the following interface, combined with the above process pattern.

 Public Interface Statementcallback {    publicvoid  method3 ();}

The so-called customization is: I'll call you when I need it.

 Public classSonextendsfather{ Public voidmethod3 () {System.out.println ("Implement by Son"); }} Public classMain { Public Static voidMain (string[] args) {Father Patten=NewSon (); Patten.templatemethod (NewStatementcallback () {@Override Public voidmethod3 () {System.out.println ("Implement by User,callback");    }        }); }}

    • SOURCE Analysis

Its various methods are finally forwarded to this method, the whole method is to apply for connection, execute SQL, get results , finally release the connection, where the red label is the embodiment of the custom. It encapsulates a number of upper-level methods, such as Queryforlist,queryformap, that return the data structure it encapsulates. and the bottom-level process is the above approach.

The way it provides the default implementation is an anonymous inner class.

Excute is designed to execute SQL, and the query method and update are designed to read and write separately.

As anyone who used to know, UPDATE returns int represents the number of affects it operates, and a JDBC popular way of returning a primary key is to implement a logic that returns the primary key in update, which is the interface that it uses.

The following code overrides the callback interface so that it returns the inserted primary key.

        intCol = 0; Keyholder Keyholder=NewgeneratedKeyHolder (); Jdbctemplate.update (NewPreparedStatementCreator () { Publicpreparedstatement createpreparedstatement (Connection con)throwsSQLException {preparedstatement ps=con.preparestatement (Sql,preparedstatement.return_generated_keys);  for(inti=0;i<args.length;i++) {Ps.setobject (i+1, Args[i]); }                returnPS;        }}, Keyholder); Col= Keyholder.getkey (). Intvalue ();

The rest of the interface is not read, and for JDBC, nothing but read and write, we usually use a list and map, it can also encapsulate object, as a small ORM, it is excellent design pattern makes the database operation layer Business design is very simple and clear, and its excellent generic processing technology, is also breathtaking.

     

Spring JdbcTemplate Source Reading report

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.