Home Database Mysql Tutorial 用JdbcTemplateTool配合JdbcTemplate实现更便捷的数据库操作

用JdbcTemplateTool配合JdbcTemplate实现更便捷的数据库操作

Jun 07, 2016 pm 03:47 PM
Cooperate

JdbcTemplateTool Spring 出品的 JdbcTemplate 对于不想使用hibernate或者ibatis那样需要大量学习成本而且还想获得对象化的人来说是很好用的。但是 JdbcTemplate还是有很多不足之处或者说是缺点。比如你没法像hibernate那样直接传一个对象给它让他拆分成sql

JdbcTemplateTool

用JdbcTemplateTool配合JdbcTemplate实现更便捷的数据库操作

Spring 出品的 JdbcTemplate 对于不想使用hibernate或者ibatis那样需要大量学习成本而且还想获得对象化的人来说是很好用的。但是 JdbcTemplate还是有很多不足之处或者说是缺点。比如你没法像hibernate那样直接传一个对象给它让他拆分成sql并保存起来,当然这也是可以理解的,毕竟它并没有要求你去写 hbm.xml 文件所以无法知道你哪些字段要映射,哪些不要等等。又比如JdbcTemplate 可以帮忙把一个查询结果传化为一个对象列表,但是你需要查阅一些资料才知道要用 BeanPropertyRowMapper 。如果下次要用的时候又忘记了这个类,又要查一次或者翻以前的代码来看,其实完全可以提供一个方法直接传一个PO类进去自动创建 BeanPropertyRowMapper 。基于以上的一些不足之处,我建立了 JdbcTemplateTool 它有以下特性:

  • 把查询结果转换为PO列表,不需要调用 BeanPropertyRowMapper
  • 传一条统计sql比如 a select count(1) from table 可以直接返回一个数字作为结果,不需要自己实现中间步骤。
  • 可以直接把一个PO类存到数据库
  • 通过PO类和一个id可以获取到该对象
  • 通过PO类可以直接update数据库记录
  • 不需要实现 BatchPreparedStatementSetter, 就可以批量update
  • 通过一个对PO对象删除对应的数据库记录
  • 依然可以使用原始的 JdbcTemplate

目前只在mysql上测试.

Maven 依赖

<dependency>
  <groupid>org.crazycake</groupid>
  <artifactid>jdbctemplatetool</artifactid>
  <version>1.0.4-RELEASE</version>
</dependency>
Copy after login


快速开始

STEP 1. 创建一个maven项目

创建一个maven项目叫 testjtt. 添加 jdbctemplatetool 依赖到 pom.xml. 再添加以下依赖到 pom.xml.

<dependency>
  <groupid>junit</groupid>
  <artifactid>junit</artifactid>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
    <version>3.2.2.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupid>com.mchange</groupid>
    <artifactid>c3p0</artifactid>
    <version>0.9.2.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    <version>5.1.19</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupid>org.springframework</groupid>
    <artifactid>spring-test</artifactid>
    <version>3.2.2.RELEASE</version>
    <scope>test</scope>
</dependency>
Copy after login


最好使用 1.6+ jdk. 我并没有在 1.5 下测试

STEP 2. 创建测试数据库

创建一个测试的数据库叫 jtt_test 创建一个用户 travis 不要分配密码. 赋予jtt_test的权限给 travis .

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

创建一张表 employee 插入一些测试数据.

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);
Copy after login


STEP 3. 配置一下spring

在test文件夹下创建 resources 文件夹. 添加 resources 到 source folder 修改输出为 target/test-classes 创建 spring.xml 在 test/resources 里面

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="jdbcUrl"><value>jdbc:mysql://localhost:3306/jtt_test?characterEncoding=utf8</value></property>
        <property name="driverClass"><value>com.mysql.jdbc.Driver</value></property>
        <property name="user"><value>travis</value></property>
        <property name="password"><value></value></property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">   
         <property name="dataSource" ref="dataSource"></property>   
    </bean>

    <bean id="jdbcTemplateTool" class="org.crazycake.jdbcTemplateTool.JdbcTemplateTool">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
</beans>
Copy after login


STEP 4. 创建PO类

创建 Employee.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;
    }
}
Copy after login


STEP 5. 创建测试用例

创建 HelloJTTTest.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();
        }
    }
}
Copy after login


STEP 6. 启动!

运行测试用例,等待绿色条。然后去数据库会看到多了一条记录 :

id name join_date age
4 billy 2014-09-24 22:51:20 33

高级教程

以下是各个方法的详细介绍

list

把查询结果转换为PO列表,不需要调用 BeanPropertyRowMapper 。 自动根据数据库的列将下划线转为驼峰命名规则映射类的属性.

@Test
public void testList(){
    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);
    List<employee> es = jtt.list("select * from employee where age <br>
<br>

<h2>
count</h2>
<p>
传<span>一条统计sql比如 a </span><code>select
 count(1) from table</code><span> 可以直接返回一个数字作为结果,不需要自己实现中间步骤。</span></p>
<p>
</p>
<pre class="brush:php;toolbar:false">@Test
public 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));
    }
Copy after login


save

可以直接把一个PO类存到数据库。如果你不想把某个列映射为数据库字段可以使用 @Trasient 注解在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;
    }
}
Copy after login

这个字段会被跳过

@Test
public 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);
}
Copy after login


get

过PO类和一个id可以获取到该对象。但是前提是需要在主键的getter上标上 @Id 注解

@Id
public Integer getId() {
    return id;
}
Copy after login


例子

@Test
public 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"));
}
Copy after login


update

自动根据PO类更新数据库. 记得增加 @Id .

@Test
public 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);
}
Copy after login


batchUpdate

批量更新

@Test
public void testBatchUpdate() throws SQLException, IOException {
    build();

    JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);

    List<object> params = new ArrayList<object>();
    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);

}</object></object>
Copy after login


delete

删除数据库对象

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


getJdbcTemplate

你依然可以使用原始的 JdbcTemplate. 调用 JdbcTemplateTool.getJdbcTemplate() to getJdbcTemplate 就可以了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

How do you create indexes on JSON columns? How do you create indexes on JSON columns? Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

How do you represent relationships using foreign keys? How do you represent relationships using foreign keys? Mar 19, 2025 pm 03:48 PM

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)? How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)? Mar 18, 2025 pm 12:00 PM

Article discusses securing MySQL against SQL injection and brute-force attacks using prepared statements, input validation, and strong password policies.(159 characters)

See all articles