Use JdbcTemplateTool with JdbcTemplate for more convenient database operations

Source: Internet
Author: User
JdbcTemplate produced by JdbcTemplateToolSpring is very useful for people who do not want to use hibernate or ibatis that it requires a lot of learning costs and want to get object objects. However, JdbcTemplate still has many shortcomings or disadvantages. For example, you cannot directly upload an object like hibernate to split it into SQL statements.

JdbcTemplate produced by JdbcTemplateTool Spring is very useful for people who do not want to use hibernate or ibatis that it requires a lot of learning costs and want to get object objects. However, JdbcTemplate still has many shortcomings or disadvantages. For example, you cannot directly upload an object like hibernate to split it into SQL statements.

JdbcTemplateTool

The JdbcTemplate produced by Spring is very useful for people who do not want to use hibernate or ibatis that it requires a lot of learning costs and want to get the object. However, JdbcTemplate still has many shortcomings or disadvantages. For example, you cannot directly upload an object like hibernate to split it into SQL statements and save it. Of course, this is understandable. After all, it does not require you to write hbm. the xml file does not know which fields you want to map and which fields do not need to be mapped. For example, JdbcTemplate can be used to pass a query result into an object list, but you need to check some information before you can use BeanPropertyRowMapper. If you forget this class when you use it next time, you can check it again or refer to the previous Code. In fact, you can provide a method to directly upload a PO class to automatically create BeanPropertyRowMapper. Based on the above shortcomings, I established JdbcTemplateTool which has the following features:

  • Converts the query result to a PO list without callingBeanPropertyRowMapper
  • Upload a statistical SQL statement, such asselect count(1) from tableYou can directly return a number as the result without performing any intermediate steps.
  • You can directly store a PO class to the database.
  • This object can be obtained through the PO class and an id.
  • You can use the PO class to directly update database records.
  • BatchPreparedStatementSetter can be updated in batches.
  • Deletes the corresponding database record through a PO object
  • You can still use the originalJdbcTemplate

Currently, it is only tested on mysql.

Maven dependency

   
  
   org.crazycake
    jdbctemplatetool  
  
   1.0.4-RELEASE
  
 


Quick Start STEP 1. Create a maven Project

Create a maven project namedtestjtt. Add the jdbctemplatetool dependency to pom. xml. Then add the following dependency to pom. xml.

   
  
   junit
    junit  
  
   4.11
    
  
   test
  
 
     
  
   org.springframework
      spring-context    
  
   3.2.2.RELEASE
      
  
   test
  
 
     
  
   com.mchange
      c3p0    
  
   0.9.2.1
      
  
   test
  
 
     
  
   mysql
      mysql-connector-java    
  
   5.1.19
      
  
   test
  
 
     
  
   org.springframework
      spring-test    
  
   3.2.2.RELEASE
      
  
   test
  
 


It is best to use 1.6 + jdk. I have not tested it in 1.5.

STEP 2. Create a Test Database

Creating a test database is calledjtt_testCreate a usertravisDo not assign a password. Grant the jtt_test permissiontravis.

CREATE USER 'travis'@'%' IDENTIFIED BY '';GRANT ALL ON jtt_test.* TO 'travis'@'%';flush privileges;

Create a tableemployeeInsert some test data.

DROP TABLE IF EXISTS `employee`;CREATE TABLE `employee` (  `id` int(11) NOT NULL,  `name` varchar(300) NOT NULL,  `join_date` datetime NOT NULL,  `age` int(11) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;/*Data for the table `employee` */insert  into `employee`(`id`,`name`,`join_date`,`age`) values (1,'jack','2014-09-22 00:00:00',23),(2,'ted','2014-08-30 00:00:00',25),(3,'jim','2014-06-22 00:00:00',33);


STEP 3. Configure spring

Create in the test folderresourcesFolder. AddresourcesTo source folder, change the outputtarget/test-classesCreatespring.xmlIn test/resources

 
     
          
   
    
     jdbc:mysql://localhost:3306/jtt_test?characterEncoding=utf8
    
           
   
    
     com.mysql.jdbc.Driver
    
           
   
    
     travis
    
           
   
    
       
      
              
          
      
          
       
  
 


STEP 4. Create a PO class

CreateEmployee.java

import java.sql.Timestamp;import javax.persistence.Id;public class Employee {    private Integer id;    private String name;    private Timestamp joinDate;    private Integer age;    @Id    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Timestamp getJoinDate() {        return joinDate;    }    public void setJoinDate(Timestamp joinDate) {        this.joinDate = joinDate;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}


STEP 5. Create a test case

CreateHelloJTTTest.java

import static org.hamcrest.CoreMatchers.is;import static org.junit.Assert.assertThat;import java.util.List;import org.crazycake.jdbcTemplateTool.JdbcTemplateTool;import org.junit.Test;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@ContextConfiguration(locations={"classpath:spring.xml"})public class HelloJTTTest extends AbstractJUnit4SpringContextTests{    @Test    public void testSave(){        JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);        Employee e = new Employee();        e.setId(4);        e.setName("billy");        Date now = new Date();        e.setJoinDate(new Timestamp(now.getTime()));        e.setAge(33);        try {            jtt.save(e);        } catch (Exception e1) {            e1.printStackTrace();        }    }}


STEP 6. Start!

Run the test case and wait for the green bar. Then, the database will see an additional record:

Id Name Join_date Age
4 Billy 22:51:20 33
Advanced tutorial

The following describes the methods in detail.

List

Converts the query result to a PO list without callingBeanPropertyRowMapper. Automatically converts an underscore (_) to an attribute of the ing Class Based on the database column.

@Testpublic void testList(){    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    List
 
   es = jtt.list("select * from employee where age < ? order by id desc", new Object[]{30}, Employee.class);    assertThat(new Integer(es.size()),is(2));    assertThat(es.get(1).getName(),is("jack"));}
 


Count

Upload a statistical SQL statement, such asselect count(1) from tableYou can directly return a number as the result without performing any intermediate steps.

@Testpublic void testCount() throws IOException, SQLException {    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    int total = jtt.count("select count(1) from employee", null);    assertThat(total,is(4));    }


Save

You can directly store a PO class to the database. If you do not want to map a column to a database field, you can use the @ Trasient Annotation on getter.

public class Student {    private Integer id;    private String name;    private String nothing;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Transient    public String getNothing() {        return nothing;    }    public void setNothing(String nothing) {        this.nothing = nothing;    }}

This field will be skipped

@Testpublic void testSave() throws Exception {    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    Student s = new Student();    s.setName("michael");    s.setNothing("nothing");    jtt.save(s);}


Get

This object can be obtained through the PO class and an id. However, the premise is that you need to mark the @ Id Annotation on the getter of the primary key.

@Idpublic Integer getId() {    return id;}


Example

@Testpublic void testGet() throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException, IOException, SQLException {    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    Employee e = jtt.get(Employee.class, 3);    assertThat(e.getName(),is("jim"));}


Update

Automatically update the database based on the PO class. Remember to add@Id.

@Testpublic void testUpdate() throws Exception {    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    Employee e = jtt.get(Employee.class, 1);    e.setAge(23);    jtt.update(e);}


BatchUpdate

Batch update

@Testpublic void testBatchUpdate() throws SQLException, IOException {    build();    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    List
 
   params = new ArrayList
  
   ();    Object[] p1 = new Object[]{23,"jack"};    params.add(p1);    Object[] p2 = new Object[]{29,"tim"};    params.add(p2);    jtt.batchUpdate("update employee set age = ? where name = ?", params);}
  
 


Delete

Delete database objects

@Testpublic void testDelete() throws Exception {    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);    Employee e = new Employee();    e.setId(1);    jtt.delete(e);}


GetJdbcTemplate

You can still use the originalJdbcTemplate. CallJdbcTemplateTool.getJdbcTemplate()To getJdbcTemplateYou can.

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.