search
HomeJavajavaTutorialA brief introduction to JdbcTemplate
A brief introduction to JdbcTemplateJun 25, 2017 am 11:03 AM
javagetting StartedExampleSimple

1. About JdbcTemplate

JdbcTemplate is the most basic Spring JDBC template. This template supports simple JDBC database access functions and queries based on index parameters.

Spring Data Access Template: During database operations, there is a large part of repeated work, such as transaction control, resource management, and exception handling. Spring's template classes handle these fixed parts. At the same time, application-related data access is handled in the callback implementation, including statements, binding parameters, and sorting results. In this way, we only need to care about our own data access logic.

A brief introduction to JdbcTemplate

Spring's JDBC framework takes on the work of resource management and exception handling, thus simplifying the JDBC code. We only need to write the necessary code to read and write data from the database and everything will be fine. .

2. Spring JdbcTemplate Example

Our learning goal is to write a demo to implement CRUD operations on Category.

1. Create a table

mysql to create a new database store, and then execute the following sql:

create table Category (
Id int not null,
Name varchar(80) null,constraint pk_category primary key (Id)
);INSERT INTO category(id,Name) VALUES (1,'女装');INSERT INTO category(id,Name) VALUES (2,'美妆');INSERT INTO category(id,Name) VALUES (3,'书籍');
db_store. sql

2. The IDE I use is IdeaIU, I build the project through maven and configure spring through xml. The completed code structure is:

A brief introduction to JdbcTemplate

3. Create the entity class Category

public class Category{
    private int cateId;

    private String cateName;

    public int getCateId() {
        return cateId;
    }

    public void setCateId(int cateId) {
        this.cateId = cateId;
    }

    public String getCateName() {
        return cateName;
    }

    public void setCateName(String cateName) {
        this.cateName = cateName;
    }

    @Override
    public String toString() {
        return "id="+cateId+" name="+cateName;
    }
}

 

4. Modify pom.xml, introduce related dependencies.

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- Mysql数据库链接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

 

5. Configure applicationContext.xml

You need to configure dataSource as the data source of jdbcTemplate. Then configure the CategoryDao bean and construct the jdbcTemplate object. The complete applicationContext.xml is as follows:

<?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 ">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/store"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean id="categoryDao" class="CategoryDao">
        <constructor-arg ref="jdbcTemplate"></constructor-arg>
    </bean>
</beans>

 

6. Data access implementation class CategoryDao

The CategoryDao constructor contains the parameter jdbcTemplate, and then implements Commonly used data access operations. As you can see, we only need to pay attention to the specific sql statement. In addition, lambda syntax is used in the getById() and getAll() methods.

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by 陈敬 on 2017/6/6.
 */
public class CategoryDao {
    private JdbcTemplate jdbcTemplate;

    public CategoryDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int add(Category category) {
        String sql = "INSERT INTO category(id,name)VALUES(?,?)";
        return jdbcTemplate.update(sql, category.getCateId(), category.getCateName());
    }

    public int update(Category category) {
        String sql = "UPDATE Category SET Name=? WHERE Id=?";
        return jdbcTemplate.update(sql, category.getCateName(), category.getCateId());
    }

    public int delete(int id) {
        String sql = "DELETE FROM Category WHERE Id=?";
        return jdbcTemplate.update(sql, id);
    }

    public int count(){
        String sql="SELECT COUNT(0) FROM Category";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    public Category getById(int id) {
        String sql = "SELECT Id,Name FROM Category WHERE Id=?";
        return jdbcTemplate.queryForObject(sql, (ResultSet rs, int rowNumber) -> {
            Category category = new Category();
            category.setCateId(rs.getInt("Id"));
            category.setCateName(rs.getString("Name"));
            return category;
        }, id);
    }

    public List<Category> getAll(){
        String sql="SELECT Id,Name FROM Category";

        List<Category> result=jdbcTemplate.query(sql, (resultSet, i) -> {
            Category category = new Category();
            category.setCateId(resultSet.getInt("Id"));
            category.setCateName(resultSet.getString("Name"));
            return category;
        });

        return result;
    }
}

 

7. Test

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testCategoryDao {
    @Autowired
    private CategoryDao categoryDao;

    @Test
    public void testAdd() {
        Category category = new Category();
        category.setCateId(4);
        category.setCateName("母婴");

        int result = categoryDao.add(category);
        System.out.println(result);
    }

    @Test
    public void testUpdate() {
        Category category = new Category();
        category.setCateId(4);
        category.setCateName("男装");

        int result = categoryDao.update(category);
        System.out.println(result);
    }


    @Test
    public void testGetById() {
        int id = 4;
        Category category = categoryDao.getById(id);
        System.out.println(category.toString());
    }

    @Test
    public void testGetAll() {
        List<Category> categories = categoryDao.getAll();
        for (Category item : categories) {
            System.out.println(item);
        }
    }

    @Test
    public void testCount() {
        int count = categoryDao.count();
        System.out.println(count);
    }

    @Test
    public void testDelete() {
        int id = 4;
        int result = categoryDao.delete(id);
        System.out.println(result);
    }
}

The above is the detailed content of A brief introduction to JdbcTemplate. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools