日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring JDBC-NamedParameterJdbcTemplate模板类

發布時間:2025/3/21 javascript 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring JDBC-NamedParameterJdbcTemplate模板类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

  • 概述
  • 示例
    • BeanPropertySqlParameterSource 使用示例
    • MapSqlParameterSource使用示例
  • NamedParameterJdbcTemplate 支持 in 的操作
    • PrepareStatement的缺陷
    • NamedParameterJdbcTemplate的操作示例
  • 示例源碼

概述

除了標準的JdbcTemplate外,Spring還提供了兩個易用的JDBC模板類

  • SimpleJdbcTemplate 封裝了JdbcTemplate,將常用的API開放出來 . 這里暫不討論
  • NamedParameterJdbcTemplate 提供命名參數綁定的功能。

在低版本的Spring 中, 用戶只能使用“?”占位符聲明參數,并使用索引號綁定參數,必須要保證參數的索引號和SQL語句中的占位符“?”的位置正確匹配。

NamedParameterJdbcTemplate模板了支持命名參數變量的SQL,位于org.springframework.jdbc.namedparam包中,該包中還定義了一個用于承載命名參數的SqlParameterSource接口

  • BeanPropertySqlParameterSource:該實現類是將一個JavaBean對像封裝成一個參數源,以便通過JavaBean屬性名和SQL語句中的命名參數匹配的方式綁定參數

  • MapSqlparameterSource:該實現類內部通過一個Map存儲參數,可以通過addValue(String paramName , Object value) 或 addValue(Map value)添加參數,并通過參數鍵名和SQL語句的命名參數的方式綁定參數。


示例

BeanPropertySqlParameterSource 使用示例

package com.xgj.dao.namedParameterJdbcTemplate.dao;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository;import com.xgj.dao.namedParameterJdbcTemplate.domain.Artisan;/*** * * @ClassName: ArtisanNJDaoImpl* * @Description: @Repository標注的DAO層,受Spring管理* * @author: Mr.Yang* * @date: 2017年9月30日 上午12:42:26*/@Repository public class ArtisanNJDaoImpl implements ArtisanNJDao {private NamedParameterJdbcTemplate namedParameterJdbcTemplate;private final static String insertArtisanSql = "insert into artisan(artisan_name) values(:artisanName)";/*** * * @Title: setNamedParameterJdbcTemplate* * @Description: 自動注入namedParameterJdbcTemplate* * @param namedParameterJdbcTemplate* * @return: void*/@Autowiredpublic void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;}@Overridepublic void addArtisan(Artisan artisan) {// 定義命名參數SqlParameterSource sps = new BeanPropertySqlParameterSource(artisan);// 使用模板類方法namedParameterJdbcTemplate.update(insertArtisanSql, sps);}}

在SQL語句中聲明命名參數的格式為

:paranName

比如values(:artisanName) ,多個參數使用逗號分隔。

在這個示例中,使用BeanPropertySqlParameterSource提供數據源,它接收一個JavaBean作為構造函數的入參,調用namedParameterJdbcTemplate.update(insertArtisanSql, sps)執行插入數據的而操作。

配置文件

<?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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 掃描類包,將標注Spring注解的類自動轉化Bean,同時完成Bean的注入 --><context:component-scan base-package="com.xgj.dao.namedParameterJdbcTemplate" /><!-- 使用context命名空間 配置數據庫的properties文件 --><context:property-placeholder location="classpath:spring/jdbc.properties" /><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close" p:driverClassName="${jdbc.driverClassName}"p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /><!-- 定義 namedParameterJdbcTemplate--><bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"><constructor-arg ref="dataSource"/></bean></beans>

注意NamedParameterJdbcTemplate的配置,使用構造函數。


Domain

package com.xgj.dao.namedParameterJdbcTemplate.domain;import java.io.Serializable;public class Artisan implements Serializable {private static final long serialVersionUID = 1L;private String artisanId;private String artisanName;public String getArtisanId() {return artisanId;}public void setArtisanId(String artisanId) {this.artisanId = artisanId;}public String getArtisanName() {return artisanName;}public void setArtisanName(String artisanName) {this.artisanName = artisanName;}}

Artisan擁有兩個屬性,我們這里沒有插入ID,暫且忽略。 其中 artisanName 這個屬性和 SQL語句中的命名參數匹配,參數即按照這個匹配關系進行綁定。


單元測試

package com.xgj.dao.namedParameterJdbcTemplate.dao;import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.xgj.dao.namedParameterJdbcTemplate.domain.Artisan;public class ArtisanNJDaoImplTest {ClassPathXmlApplicationContext ctx = null;ArtisanNJDaoImpl artisanNJDaoImpl = null;@Beforepublic void initContext() {// 啟動Spring 容器ctx = new ClassPathXmlApplicationContext("classpath:com/xgj/dao/namedParameterJdbcTemplate/conf_namedParameterJdbcTemplate.xml");artisanNJDaoImpl = ctx.getBean("artisanNJDaoImpl",ArtisanNJDaoImpl.class);System.out.println("initContext successfully");}@Testpublic void queryTeacherById() {Artisan artisan = new Artisan();artisan.setArtisanName("ArtisanNJ");artisanNJDaoImpl.addArtisan(artisan);}@Afterpublic void closeContext() {if (ctx != null) {ctx.close();}System.out.println("close context successfully");} }

結果:
查看下數據庫是否插入成功 (只是演示,忽略ID…)


MapSqlParameterSource使用示例

如果有數據表記錄沒有對應的領域對象,則用戶可以直接使用MapSqlparameterSource達到綁定參數的目的。

public void addArtisanWithMapSqlParameterSource(Artisan artisan) {// 使用MapSqlParameterSource綁定參數MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource().addValue("artisanName", artisan.getArtisanName());// 使用模板類方法namedParameterJdbcTemplate.update(insertArtisanSql,mapSqlParameterSource);}

由于MapSqlParameterSource中的大多數方法都能返回對象本身,所以可以將幾個參數的調用串成一個鏈,假設Artisan還有個artisanSex屬性,如下

MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource().addValue("artisanName", artisan.getArtisanName()).addValue("artisanSex",artisan.getArtisanSex);

由于這個原因,使用方法調用鏈模式設計的API很容易使用。


單元測試

@Testpublic void queryTeacherById() {// Artisan artisan = new Artisan();// artisan.setArtisanName("ArtisanNJ");// artisanNJDaoImpl.addArtisan(artisan);Artisan artisan = new Artisan();artisan.setArtisanName("ArtisanMS");artisanNJDaoImpl.addArtisanWithMapSqlParameterSource(artisan);}

數據庫結果


NamedParameterJdbcTemplate 支持 in 的操作

PrepareStatement的缺陷

如果我們想查找artisan_id在 1 ,3 , 5 中的數據, PrepareStatement對in的操作只能動態拼接

String in_data = "1,3,5"; pst = conn.prepareStatement("select artisan_name from artisan where artisan_id in (?)"); pst.setString(1,in_data);

使用傳統的prepareStatement是動態設定參數的,也就是生成 select artisan_name from artisan where artisan_id in (?) ,一個 ? 代表一個參數,pst.setString(1,”1,3,5”) 就相當于 select artisan_name from artisan where artisan_id in (“1,3,5”) ,這個SQL是查找artisan_id為 “1,3,5”的記錄,而不是在 1,3,5中記錄。


NamedParameterJdbcTemplate的操作示例

NamedParameterJdbcTemplate可以很好地解決上述問題呢。

....private final static String selectArtisanByIds = "select artisan_name from artisan where artisan_id in (:artisanId)";....public List<Artisan> getArtisanByIds(List<String> artisanIds) {final List<Artisan> artisanList = new ArrayList<Artisan>();// 使用MapSqlParameterSource綁定參數MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();mapSqlParameterSource.addValue("artisanId", artisanIds);namedParameterJdbcTemplate.query(selectArtisanByIds,mapSqlParameterSource, new RowCallbackHandler() {@Overridepublic void processRow(ResultSet rs) throws SQLException {Artisan artisan = new Artisan();artisan.setArtisanName(rs.getString("artisan_name"));// 加入集合artisanList.add(artisan);}});return artisanList;}

單元測試

@Testpublic void queryTeacherById() {List<String> artisanIds = new ArrayList<String>();artisanIds.add("1");artisanIds.add("3");artisanIds.add("5");List<Artisan> artisans = artisanNJDaoImpl.getArtisanByIds(artisanIds);for (Artisan artisan : artisans) {System.out.println("artisanName:" + artisan.getArtisanName());}}

輸出:

2017-09-30 02:01:27,648 INFO [main] (AbstractApplicationContext.java:583) - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5f0ab5d: startup date [Sat Sep 30 02:01:27 BOT 2017]; root of context hierarchy 2017-09-30 02:01:27,777 INFO [main] (XmlBeanDefinitionReader.java:317) - Loading XML bean definitions from class path resource [com/xgj/dao/namedParameterJdbcTemplate/conf_namedParameterJdbcTemplate.xml] initContext successfully artisanName:Xiao2 artisanName:Xiao0 artisanName:Xiao4 2017-09-30 02:01:30,387 INFO [main] (AbstractApplicationContext.java:984) - Closing org.springframework.context.support.ClassPathXmlApplicationContext@5f0ab5d: startup date [Sat Sep 30 02:01:27 BOT 2017]; root of context hierarchy close context successfully

示例源碼

代碼已托管到Github—> https://github.com/yangshangwei/SpringMaster

總結

以上是生活随笔為你收集整理的Spring JDBC-NamedParameterJdbcTemplate模板类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。