Spring的连接数据库以及JDBC模板(实例讲解)

作者:夜孤寒 时间:2023-03-21 05:56:36 

前言

今天介绍的是关于Spring的数据库连接以及Jdbc模板的相关API方法,虽然在学习了hibernate之后,会知道实现数据库连接一般都是使用hibernate等持久化框架来实现的。但是,很多时候一些涉及到事务的东西使用这些框架并不能够实现,所以我们还需要结合spring来实现相关的需要。

一、创建工程、导包

要想使用Spring的jdbc模板前,还需要导入相关的jar包:

Spring的连接数据库以及JDBC模板(实例讲解)

二、进行相关的bean的创建以及工具类的编写

2.1在数据库中创建了两张表,使用spring的jdbcTemplate中的API方法对这两张表进行操作


CREATE TABLE `t_dept` (
`deptid` int(11) NOT NULL,
`deptname` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
`remark` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`deptid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_bin;

CREATE TABLE `user` (
`USER_ID` int(11) NOT NULL,
`USER_NAME` varchar(11) DEFAULT NULL,
`USER_PASSWORD` varchar(11) DEFAULT NULL,
`USER_ADDRESS` varchar(25) DEFAULT NULL,
PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.2创建实体bean


package com.bean;
/**
* 创建t_dept表对应的表
* @author 夜孤寒
* @version 1.1.1
*
*/
public class DeptBean {
private int deptid;
private String deptname;
private String remark;
public DeptBean() {
 super();
}
public DeptBean(int deptid, String deptname, String remark) {
 super();
 this.deptid = deptid;
 this.deptname = deptname;
 this.remark = remark;
}
public int getDeptid() {
 return deptid;
}
public void setDeptid(int deptid) {
 this.deptid = deptid;
}
public String getDeptname() {
 return deptname;
}
public void setDeptname(String deptname) {
 this.deptname = deptname;
}
public String getRemark() {
 return remark;
}
public void setRemark(String remark) {
 this.remark = remark;
}
}

2.3创建spring的工具类——SpringUtil.java


package com.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* 读取配置文件的工具类,实现了类似工厂模式的方式
*
* @author 夜孤寒
* @version 1.1.1
*/
public class SpringUtil {
// 定义属性
private static ApplicationContext context;
// 读取配置文件
static {
 context = new ClassPathXmlApplicationContext("spring.xml");
}

// 定义一个方法,判断bean是否为空,如果不为空的,获取这个bean
public static Object getBean(String beanName) {
 // 定义一个空对象
 Object obj = null;
 // 如果beanName不为空的话,那么根据这个beanName获取到bean对象,赋值给obj并返回
 if (beanName != null && !beanName.equals("")) {
  obj = context.getBean(beanName);
 }
 return obj;
}
}

2.4进行配置文件的相关配置——spring.xml文件的配置

因为要介绍的API方法可能比较多,所以一次性将写过的xml全部粘贴了,读者可以根据对应的配置,去对应到相应的类中:


<?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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!-- 方式一:
  配置使用IOC:直接引用
 -->
 <!-- 首先需要引入一个驱动,然後到這驱动类下面,去查看他的源代码,一下是mysql需要注入的对象 -->
 <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test"></property>
  <property name="username" value="root"></property>
  <property name="password" value="root"></property>
 </bean>

<!-- 使用DI注入的构造方法注入的方式来注入,并且查询我们的数据库中的数据。
   注意这里我们还需要一我们之前的dataSource作为引用
 -->
 <bean name="testMain_2" class="com.jdbc.TestMain_2">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 使用我们的模板来获取我们的数据库中的数据 -->
 <bean name="testMain_3" class="com.jdbc.TestMain_3">
  <!-- 首先我们还是需要引入我们的数据库资源,也就是我们之前已经配置过的dataSource -->
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 方式四 -->
 <!-- 配置我们模板,然后在类就只要将这个模板用构造方法的方式注入就可以了 -->
 <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"></property>
 </bean>
 <!-- 配置我们的testMain_4,然后引用我们上面配置的模板 -->
 <bean name="testMain_4" class="com.jdbc.TestMain_4">
  <property name="jdbcTemplate" ref="jdbcTemplate"></property>
 </bean>

<!-- 方式五:
   直接继承JdbcDaoSupport这个父类,然后用里面的方法获取到模板,
   从而获取到数据。
   备注:这个是最完美的获取数据的方式,以后一般都是使用这种方式!!!
 -->
 <bean name="testMain_5" class="com.jdbc.TestMain_5">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 使用spring配置的方式操作我们的DDL语句 -->
 <bean name="testMain_6" class="com.jdbc.TestMain_6">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 使用spring配置的方式操作我们的DML语句 -->
 <bean name="testMain_7" class="com.jdbc.TestMain_7">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 使用JdbcTemplate模板中的命名参数来操作我们的DML语句 -->
 <bean name="testMain_8" class="com.jdbc.TestMain_8">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

<!-- 使用JdbcTemplate模板对于查询语句的封装 -->
 <bean name="testMain_9" class="com.jdbc.TestMain_9">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

</beans>

2.5介绍spring对于jdbc的模板的支持

(1)数据库的连接

对应xml中的配置为:


<!-- 方式一:
  配置使用IOC:直接引用
 -->
 <!-- 首先需要引入一个驱动,然後到這驱动类下面,去查看他的源代码,一下是mysql需要注入的对象 -->
 <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  <property name="url" value="jdbc:mysql://localhost:3306/spring_jdbc_test"></property>
  <property name="username" value="root"></property>
  <property name="password" value="root"></property>
 </bean>

对应的测试类:


package com.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.util.SpringUtil;
/**
* 连接数据库的测试类
* @author 夜孤寒
* @version 1.1.1
*
*/
public class TestMain_1 {
public static void main(String[] args) {
 /*
  * 本来需要用applicationContext获取到我们的bean对象,
  * 这里使用工厂类的方法将之独立出来,具体使用见SpringUtil.java
  */
 DataSource datasource=(DataSource)SpringUtil.getBean("dataSource");
 Connection conn=null;
 try{
  conn=datasource.getConnection();
 }catch(SQLException e){
  e.printStackTrace();
 }
 System.out.println(conn);//测试是否能够输出连接
}
}

测试结果:

Spring的连接数据库以及JDBC模板(实例讲解)

由此可见测试成功可以获取到相应的数据库连接。

(2)测试从创建的user表中查询出相应的数据

对应xml配置为:


<!-- 使用DI注入的构造方法注入的方式来注入,并且查询我们的数据库中的数据。
   注意这里我们还需要一我们之前的dataSource作为引用
 -->
 <bean name="testMain_2" class="com.jdbc.TestMain_2">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

对应的测试类为:


package com.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;

import javax.sql.DataSource;

import com.mysql.jdbc.Statement;
import com.util.SpringUtil;

/**
* 从创建的user表中查询相关的数据
*
* @author 夜孤寒
* @version 1.1.1
*/
public class TestMain_2 {
// 使用构造方法注入
public DataSource datasource;

public void setDataSource(DataSource datasource) {
 this.datasource = datasource;
}

/**
 * 从user表中获取所有数据
 */
public void list() {
 /*
  * 在我们的main方法中获取到我们的datasource, 然后就能够获取连接,并且获取到数据库中的数据。
  */
 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 String sql = "select * from user";
 try {
  conn = datasource.getConnection();
  stmt = (Statement) conn.createStatement();
  rs = stmt.executeQuery(sql);
  while (rs.next()) {
   System.out.println(rs.getInt("user_id") + "\t" + rs.getString("user_name") + "\t"
     + rs.getString("user_password") + "\t" + rs.getString("user_address"));
  }
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  /*
   * 需要自己关闭资源
   */
 }
}

public static void main(String[] args) {
 // 获取到我们bean对象
 TestMain_2 testMain_2 = (TestMain_2) SpringUtil.getBean("testMain_2");
 // 调用我们的list方法
 testMain_2.list();
}
}

测试结果:

Spring的连接数据库以及JDBC模板(实例讲解)

备注:本测试类,使用的是常用的纯粹的jdbc获取数据的方式。

(3)使用JdbcTemplate这个类来获取到后端的数据

对应的xml文件的配置为:


<!-- 使用我们的模板来获取我们的数据库中的数据 -->
 <bean name="testMain_3" class="com.jdbc.TestMain_3">
  <!-- 首先我们还是需要引入我们的数据库资源,也就是我们之前已经配置过的dataSource -->
  <property name="dataSource" ref="dataSource"></property>
 </bean>

对应的测试类:


package com.jdbc;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.util.SpringUtil;
/**
* 使用jdbcTemplate这个类来获取后台数据
* @author 夜孤寒
*
*/
public class TestMain_3 {
// 使用构造方法注入
public DataSource datasource;

public void setDataSource(DataSource datasource) {
 this.datasource = datasource;
}

public void list() {
 /*
  * 使用我们JdbcTemplate模板来获取我们的数据
  */
 JdbcTemplate jdbcTemplate=new JdbcTemplate(this.datasource);
 String sql="select * from user";
 List<Map<String, Object>>userlist=jdbcTemplate.queryForList(sql);
 for(Map<String, Object>rowMap:userlist){
  System.out.println(rowMap);
 }
}

public static void main(String[] args) {
 //获取到我们bean对象
 TestMain_3 testMain_3=(TestMain_3)SpringUtil.getBean("testMain_3");
 //调用我们的list方法
 testMain_3.list();
}
}

测试的结果:

Spring的连接数据库以及JDBC模板(实例讲解)

这种方式的话每次我们都要创建一个JdbcTemplate实例,这样子比较复杂,所以考虑能不能将这个类让Spring自己创建,然后在bean配置文件中引用数据源来达到目的。这就是下面要介绍的第四种方式。

(4)在配置文件中配置我们的模板类,让Spring生成需要的bean

对应的xml配置文件为:


<!-- 方式四 -->
 <!-- 配置我们模板,然后在类就只要将这个模板用构造方法的方式注入就可以了 -->
 <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"></property>
 </bean>
 <!-- 配置我们的testMain_4,然后引用我们上面配置的模板 -->
 <bean name="testMain_4" class="com.jdbc.TestMain_4">
  <property name="jdbcTemplate" ref="jdbcTemplate"></property>
 </bean>

对应的测试类为:


package com.jdbc;

import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

import com.util.SpringUtil;

/**
* 在配置文件中配置模板,让spring去创建模板类
*
* @author 夜孤寒
* @version 1.1.1
*/
public class TestMain_4 {
// 使用构造方法的方式注入template
public JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
 this.jdbcTemplate = jdbcTemplate;
}

public void list() {
 /*
  * 使用我们IOC注入模板,然后引用这个使用IOC注入的模板, 最后取出我们的数据
  */
 String sql = "select USER_NAME from user";
 List<Map<String, Object>> userlist = this.jdbcTemplate.queryForList(sql);
 for (Map<String, Object> rowMap : userlist) {
  System.out.println(rowMap);
 }
}

public static void main(String[] args) {
 // 获取到我们bean对象
 TestMain_4 testMain_4 = (TestMain_4) SpringUtil.getBean("testMain_4");
 // 调用我们的list方法
 testMain_4.list();
}
}

测试结果:

Spring的连接数据库以及JDBC模板(实例讲解)

这种方式仍旧需要在xml中配置,而在spring中还有一种更加方便的方式就是直接继承JdbcDaoSupport这个类,这种方式是最简单的,也是最常用的方式。下面笔者就简单介绍一下这种方式的使用。

(5)继承JdbcDaoSupport类来获取数据库中的数据

对应的xml文件中的配置为:


<!-- 方式五:
   直接继承JdbcDaoSupport这个父类,然后用里面的方法获取到模板,
   从而获取到数据。
   备注:这个是最完美的获取数据的方式,以后一般都是使用这种方式!!!
 -->
 <bean name="testMain_5" class="com.jdbc.TestMain_5">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

对应的测试类为:


package com.jdbc;

import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.util.SpringUtil;
/**
* 继承JdbcDaoSupport来获取模板,再通过模板来获取数据
* @author 夜孤寒
* @version 1.1.1
*
*/
public class TestMain_5 extends JdbcDaoSupport {
/*
 * 不使用DI注入的方式,直接继承一个上述的父类, 观察上述的父类,发现在这个父类里面已经实现了类似注入JdbcTemplate模板。
 */

public void list() {
 String sql = "select * from user";
 List<Map<String, Object>> userlist = this.getJdbcTemplate().queryForList(sql);
 for (Map<String, Object> rowMap : userlist) {
  System.out.println(rowMap);
 }
}

public static void main(String[] args) {
 // 获取到我们bean对象
 TestMain_5 testMain_5 = (TestMain_5) SpringUtil.getBean("testMain_5");
 // 调用我们的list方法
 testMain_5.list();
}
}

测试结果为:

Spring的连接数据库以及JDBC模板(实例讲解)

(6)使用Spring注入的方式来操作DDL语句

对应xml文件中的配置为:


<!-- 使用spring配置的方式操作我们的DDL语句 -->
 <bean name="testMain_6" class="com.jdbc.TestMain_6">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

对应的测试类为:


package com.jdbc;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.util.SpringUtil;

/**
* 使用spring注入的方式进行DDL操作
*
* @author 夜孤寒
* @version 1.1.1
*
*/
public class TestMain_6 extends JdbcDaoSupport {
/*
 * 创建表
 */
public void create() {
 StringBuffer createSQL = new StringBuffer();
 createSQL.append("create table T_Temp_XX(id int,testname varchar(30))");
 this.getJdbcTemplate().execute(createSQL.toString());
}

/*
 * 修改表,这里面可以添加或者删除某一个属性列
 */
public void alter() {
 StringBuffer alterSQL = new StringBuffer();
 alterSQL.append("alter table T_Temp_XX add testpassword varchar(30)");
 this.getJdbcTemplate().execute(alterSQL.toString());
}

/*
 * 删除一张表
 */
public void drop() {
 StringBuffer dropSQL = new StringBuffer();
 dropSQL.append("drop table T_Temp_XX");
 this.getJdbcTemplate().execute(dropSQL.toString());
}

/*
 * 测试方法
 */
public static void main(String[] args) {
 // 获取到我们bean对象
 TestMain_6 testMain_6 = (TestMain_6) SpringUtil.getBean("testMain_6");
 // 调用我们的方法,一次调用一个方法,打开数据库观察数据库是不是已经变化了
 // testMain_6.create();
 // testMain_6.alter();
 testMain_6.drop();
}
}

经过测试可以进行DDL操作。

(7)使用spring注入的方式进行DML操作

对应xml文件中的配置:


<!-- 使用spring配置的方式操作我们的DML语句 -->
<bean name="testMain_7" class="com.jdbc.TestMain_7">
<property name="dataSource" ref="dataSource"></property>
</bean>

对应测试类:


package com.jdbc;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.util.SpringUtil;

/**
* 使用spring配置的方式操作我们的DML语句
*
* @author 夜孤寒
* @version 1.1.1
*/

public class TestMain_7 extends JdbcDaoSupport {
/*
 * statement的写法
 */
public void insert() {
 int deptid = 1;
 String deptname = "zhangsan";
 String remark = "zhangsanzhenshuai";
 StringBuffer insertSQL = new StringBuffer();
 insertSQL.append("Insert Into T_Dept(");
 insertSQL.append("deptid,deptname");
 insertSQL.append(",remark");
 insertSQL.append(") values(");
 insertSQL.append("" + deptid + ",");
 insertSQL.append("'" + deptname + "',");
 insertSQL.append("'" + remark + "'");
 insertSQL.append("");
 insertSQL.append(")");
 int rowCount = this.getJdbcTemplate().update(insertSQL.toString());
 System.out.println("rowCount影响的行数= " + rowCount);
}

/*
 * prepareStatement的写法
 */
public void update() {
 StringBuffer updateSQL = new StringBuffer();
 updateSQL.append("update t_dept set ");
 updateSQL.append("deptname = ?,");
 updateSQL.append("remark = ?");
 updateSQL.append(" where deptid=?");
 int rowCount = this.getJdbcTemplate().update(updateSQL.toString(), new PreparedStatementSetter() {
  @Override
  public void setValues(PreparedStatement ps) throws SQLException {
   ps.setString(1, "lisi");
   ps.setString(2, "lisizhenshuai");
   ps.setInt(3, 1);
  }
 });
 System.out.println("rowCount影响的行数=" + rowCount);
}

/*
 * prepareStatement的写法
 */
public void delete() {
 StringBuffer deleteSQL = new StringBuffer();
 deleteSQL.append("delete from t_dept");
 deleteSQL.append(" where deptid=?");
 /*
  * 关于对象数组的使用:对象数组的第一个元素对应的是SQL语句中的第一个参数问号
  */
 Object[] obj = { 1 };
 int rowCount = this.getJdbcTemplate().update(deleteSQL.toString(), obj);
 System.out.println("rowCount影响的行数=" + rowCount);
}

public static void main(String[] args) {
 // 获取到bean对象
 TestMain_7 testMain_7 = (TestMain_7) SpringUtil.getBean("testMain_7");
 // 测试方法
 // testMain_7.insert();
 // testMain_7.update();
 testMain_7.delete();
}
}

经测试,可以实现DML操作中的增删改查。

(8)使用JdbcTemplate模板中的命名参数来操作我们的DML语句

对应xml中的配置为:


<!-- 使用JdbcTemplate模板中的命名参数来操作我们的DML语句 -->
<bean name="testMain_8" class="com.jdbc.TestMain_8">
<property name="dataSource" ref="dataSource"></property>
</bean>

对应的测试类:


package com.jdbc;

import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.bean.DeptBean;
import com.util.SpringUtil;

/**
* 使用JdbcTemplate模板中的命名参数来操作我们的DML语句
*
* @author 夜孤寒
* @version 1.1.1
*/
public class TestMain_8 extends NamedParameterJdbcDaoSupport {
/*
 * statement的写法
 */
public void insert(boolean flag_1, boolean flag_2) {
 int deptid = 1;
 String deptname = "zhangsan";
 String remark = "zhangsanzhenshuai";
 StringBuffer insertSQL = new StringBuffer();
 insertSQL.append("insert into T_Dept(deptid");
 if (flag_1) {
  insertSQL.append(",deptname");
 }
 if (flag_2 == true) {
  insertSQL.append(",remark");
 }
 insertSQL.append(") values(");
 insertSQL.append(":deptid");
 if (flag_1 == true) {
  insertSQL.append(",:deptname");
 }
 if (flag_2 == true) {
  insertSQL.append(",:remark");
 }
 insertSQL.append(")");
 // 将数据放进我们的map中 备注:map中key的名称==命名参数的名称
 Map<String, Object> paramMap = new HashMap<String, Object>();
 paramMap.put("deptid", deptid);
 paramMap.put("deptname", deptname);
 paramMap.put("remark", remark);
 int rowCount = this.getNamedParameterJdbcTemplate().update(insertSQL.toString(), paramMap);
 System.out.println("rowCount影响的行数= " + rowCount);
}

/*
 * prepareStatement的写法
 */
public void update() {
 StringBuffer updateSQL = new StringBuffer();
 updateSQL.append("update T_Dept set");
 updateSQL.append(" deptname = :deptname,");
 updateSQL.append(" remark = :remark");
 updateSQL.append(" where deptid = :deptid");
 updateSQL.append("");
 // 获取到模板
 NamedParameterJdbcTemplate template = this.getNamedParameterJdbcTemplate();
 // 将数据放置到bean里面去
 DeptBean deptbean = new DeptBean();
 deptbean.setDeptid(1);
 deptbean.setDeptname("lisi");
 deptbean.setRemark("lisizhenshuai");
 // 使用一个bean工厂的方法将预处理我们的bean
 BeanPropertySqlParameterSource paramSource = new BeanPropertySqlParameterSource(deptbean);
 // 调用模板方法更新数据
 int rowCount = template.update(updateSQL.toString(), paramSource);
 // 输出影响的行数
 System.out.println("影响的行数rowCount=" + rowCount);
}

public static void main(String[] args) {
 // 获取到bean对象
 TestMain_8 testMain_8 = (TestMain_8) SpringUtil.getBean("testMain_8");
 // 测试方法
 // testMain_8.insert(true,true);//由这个参数来控制是不是插入某一个属性列的数据
 testMain_8.update();
}
}

(9)JdbcTemplate模板对于查询语句的封装

对应的xml文件的配置:


<!-- 使用JdbcTemplate模板对于查询语句的封装 -->
<bean name="testMain_9" class="com.jdbc.TestMain_9">
<property name="dataSource" ref="dataSource"></property>
</bean>

对应的测试类:


package com.jdbc;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.bean.DeptBean;
import com.util.SpringUtil;
/**
* JdbcTemplate模板对于查询语句的封装测试类
* @author 夜孤寒
* @version 1.1.1
*/
public class TestMain_9 extends JdbcDaoSupport{
/*
 * 最简单的一个查询
 */
public void one(){
 System.out.println("==============================");
 System.out.println("1:返回所有的对象");
 String sql="select * from t_dept order by deptid asc";
 List<Map<String, Object>>deptList=this.getJdbcTemplate().queryForList(sql);
 for(Map<String, Object>rowMap:deptList){
  System.out.println(rowMap);
 }
 System.out.println("==============================");
 System.out.println("2:返回一条对象");
 /*
  * 返回一条对象,将返回的对象使用Map的方式来接收
  */
 sql="select * from t_dept where deptid=1";
 Map<String, Object>rowMap=this.getJdbcTemplate().queryForMap(sql);
 if(rowMap!=null){
  System.out.println(rowMap);
 }
 /*
  * 使用queryForObject方法来接收一个对象:
  *  1、如果方法的第二个参数是class类型的话,表示SQL只能返回一行一列。相当于RowMapper中的SingleColumnRowMapper;
  *  2、如果方法的第二个参数是rowMapper类型的话,表示SQL语句只能返回一行多列。
  *  一行多列,默认是返回queryForMap,但是Spring允许可以对返回的行数据进行自定义的映射
  */
 /*
  * 方式一:返回的class类型
  */
 sql="select count(1) from t_dept where deptid=1";//什么意思?
 Integer dept_count=this.getJdbcTemplate().queryForObject(sql, Integer.class);
 System.out.println("dept_count="+dept_count);
 /*
  * 方式二:返回的是rowMapper的类型
  */
 sql="select * from t_dept where deptid=1";
 BeanPropertyRowMapper<DeptBean>rowMapper=new BeanPropertyRowMapper<DeptBean>(DeptBean.class);
 //需要将返回的数据转换成bean对象
 DeptBean deptbean=this.getJdbcTemplate().queryForObject(sql, rowMapper);
 System.out.println(deptbean.getDeptid()+"\t"+deptbean.getDeptname()+"\t"+deptbean.getRemark());
 System.out.println("==============================");

}
/*
 * 复杂的查询queryForXX:
 * 这个是模板封装好的查询方法
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void two(){
 //1、处理有预编译的语句
 String sql="select * from t_dept where deptname like ? order by deptid asc";
 List<Map<String, Object>>deptList=this.getJdbcTemplate().query(sql, new PreparedStatementSetter() {
  @Override
  public void setValues(PreparedStatement ps) throws SQLException {
   //查询带有"l"这个字符的所有对象
   ps.setString(1, "%l%");
  }
 },new ColumnMapRowMapper());//这里代表返回的是一个什么类型
 System.out.println(deptList);
 //2、处理带有预编译的语句,并且返回的是一个javabean
 List<DeptBean>deptList_2 = this.getJdbcTemplate().query(
   sql, new PreparedStatementSetter() {
    @Override
    public void setValues(PreparedStatement ps)
      throws SQLException {
     ps.setString(1, "%l%");

}
   }, new BeanPropertyRowMapper(DeptBean.class));
 System.out.println(deptList_2);
 //3、直接处理resultSet???????什么意思
 List<Vector<String>>deptList_3=this.getJdbcTemplate().query(sql, new PreparedStatementSetter() {

@Override
  public void setValues(PreparedStatement ps) throws SQLException {
   ps.setString(1, "%l%");
  }
 },new RowMapper() {
  @Override
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
   int deptid = rs.getInt("deptid");
   String deptname = rs.getString("deptname");
   Vector<String> vector = new Vector<String>();
   vector.add(String.valueOf(deptid));
   vector.add(deptname);
   return vector;
  }
 });
 System.out.println(deptList_3);
}

/*
 * 使用命名参数的查询:
 * 前提是首先要实例化命名参数查询的对象
 */
public void three(){//传一个bean条件,返回结果
 //实例化一个对象
 NamedParameterJdbcTemplate template=new NamedParameterJdbcTemplate(this.getDataSource());

//如果参数是javabean,那么返回值也就是javabean
 String sql="select * from t_dept where deptname like :deptname and remark like :remark";
 //创建一个bean,设置好查询的条件
 DeptBean parambean=new DeptBean();
 parambean.setDeptname("%l%");
 parambean.setRemark("%shuai%");
 //将创建好的bean放到查询语句的池子里面
 BeanPropertySqlParameterSource paramSource=new BeanPropertySqlParameterSource(parambean);
 BeanPropertyRowMapper<DeptBean> rowBean = new BeanPropertyRowMapper<DeptBean>(
   DeptBean.class);
 List<DeptBean>deptList=template.query(sql, paramSource, rowBean);
 for(DeptBean deptbean:deptList){
  System.out.println(deptbean.getDeptname()+"\t"+deptbean.getRemark());
 }
}
public static void main(String[] args) {
 //获取到bean对象
 TestMain_9 testMain_9=(TestMain_9)SpringUtil.getBean("testMain_9");
 //测试方法
//  testMain_9.one();
//  testMain_9.two();
 testMain_9.three();
}
}

今日笔者就将Spring中的JdbcTemplate模板介绍到这。

来源:http://www.cnblogs.com/Java766357768/p/7718722.html

标签:Spring,数据库,JDBC
0
投稿

猜你喜欢

  • java开发_图片截取工具实现原理

    2023-10-23 22:52:06
  • java使用链表实现约瑟夫环

    2022-03-21 18:59:35
  • Android扫描和生成二维码

    2022-09-11 22:57:16
  • SpringSecurity整合jwt权限认证的全流程讲解

    2022-02-20 09:58:36
  • Java数据类型分类与基本数据类型转换

    2023-08-10 08:33:37
  • DevExpress实现GridView当无数据行时提示消息

    2023-08-23 04:13:33
  • Java中SSM+Shiro系统登录验证码的实现方法

    2022-06-09 17:05:14
  • Java SpringBoot整合SpringCloud

    2022-11-11 15:07:46
  • Android 使用PDF.js浏览pdf的方法示例

    2021-12-08 06:11:41
  • java如何连续执行多条cmd命令

    2023-07-13 13:10:41
  • Android自定义View实现五子棋游戏

    2021-10-16 23:39:27
  • C# WinForm窗体编程中处理数字的正确操作方法

    2022-11-21 04:57:10
  • ArrayList在for循环中使用remove方法移除元素方法介绍

    2022-11-20 03:50:18
  • Android开发中Toast显示消息的方法小结

    2023-07-31 20:29:14
  • Spring代理对象导致的获取不到原生对象注解的解决

    2021-12-05 11:44:19
  • Mybatis逆工程jar包的修改和打包

    2023-06-03 09:28:14
  • 单点登录的三种方式和JWT的介绍与使用

    2023-05-19 22:10:59
  • java IO流将一个文件拆分为多个子文件代码示例

    2023-08-30 12:46:15
  • Android自定义Camera实现拍照功能

    2021-09-22 09:18:58
  • Android开发之获取短信验证码后按钮背景变化并且出现倒计时

    2022-12-21 10:09:40
  • asp之家 软件编程 m.aspxhome.com