1.项目搭建

<1>数据库表account对应的账户实体类

package domain;

import java.io.Serializable;

/**
* 账户实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money; 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 Float getMoney() {
return money;
} public void setMoney(Float money) {
this.money = money;
} @Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}

<2>账户的持久层接口及其实现类

接口类 IAccountDao

package dao;
import domain.Account; /**
* 账户的持久层接口
*/
public interface IAccountDao { /**
* 根据Id查询账户
* @param accountId
* @return
*/
Account findAccountById(Integer accountId); /**
* 根据名称查询账户
* @param accountName
* @return
*/
Account findAccountByName(String accountName); /**
* 更新账户
* @param account
*/
void updateAccount(Account account);
}

AccountDaoImpl.java

package dao.impl;
import dao.IAccountDao;
import domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import java.util.List; /**
* 账户的持久层实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao { public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
} public Account findAccountByName(String accountName) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}

2.JdbcTemplate的使用

<1>JdbcTemplate最基本用法

package jdbcTemplate;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource; /**
* JdbcTemplate最基本用法
*/
public class JdbcTemplateTest01 {
public static void main(String[] args) {
//1.准备数据源,Spring的内置数据源
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/spring");
ds.setUsername("root");
ds.setPassword("plj824"); //2.创建jdbcTemplate对象
JdbcTemplate jdbcTemplate=new JdbcTemplate();
//3.给jdbcTemplate对象设置数据源
jdbcTemplate.setDataSource(ds);
//2.执行操作
jdbcTemplate.execute("insert into account(name,money)values ('ccc',1000)");
}
}

<2>JdbcTemplate 用IOC进行依赖注入

package jdbcTemplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource; /**
* JdbcTemplate 用IOC进行依赖注入
*/
public class JdbcTemplateTest02 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); //3.执行操作
jdbcTemplate.execute("insert into account(name,money)values ('eee',1250)");
}
}

<3>JdbcTemplate的CRUD操作

package jdbcTemplate;

import domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; /**
* JdbcTemplate的CRUD操作
*/
public class JdbcTemplateTest03 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); //3.执行操作
//3.1保存
//jdbcTemplate.update("insert into account(name,money)values ('eee',1250)"); //3.2 更新
//jdbcTemplate.update("update account set name=?,money=? where id=?","test",4567,6); //3.3 删除
//jdbcTemplate.update("delete from account where id=? ",4); //3.4 查询所有
// List<Account> accounts = jdbcTemplate.query("select * from account where money > ?", new AccountRowMapper(), 1000f);
// for (Account account : accounts) {
// System.out.println(account);
// } // //查询一个
// List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
// System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0)); //查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jdbcTemplate.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
System.out.println(count); } } /**
* 定义Account的封装策略
*/
class AccountRowMapper implements RowMapper<Account> {
/**
* 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
*
* @param rs
* @param rowNum
* @return
* @throws SQLException
*/
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}

<4>bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--配置账户的持久层-->
<bean id="accountDao" class="dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean> <!--配置jdbcTemplate,注意:JdbcTemplate这个类是在jar包中,无法使用setter方法进行注入,只能用xml配置-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <!--配置数据源-->
<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/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="plj824"></property>
</bean>
</beans>

12 Spring JdbcTemplate的使用的更多相关文章

  1. Spring JdbcTemplate 的使用与学习(转)

    紧接上一篇 (JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中.辅助的文档) Spring DAO支持 http://ww ...

  2. 使用Spring JDBCTemplate简化JDBC的操作

    使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...

  3. Spring JDBCTemplate 简单使用

    Spring JDBCTemplate applicationContext.xml配置 <?xml version="1.0" encoding="UTF-8&q ...

  4. 【Spring】Spring的数据库开发 - 2、Spring JdbcTemplate的常用方法(execute、update、query)

    Spring JdbcTemplate的常用方法 文章目录 Spring JdbcTemplate的常用方法 execute() update() query() 简单记录-Java EE企业级应用开 ...

  5. 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析

    Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...

  6. (转)Spring JdbcTemplate 方法详解

    Spring JdbcTemplate方法详解 文章来源:http://blog.csdn.net/dyllove98/article/details/7772463 JdbcTemplate主要提供 ...

  7. [转]Spring JdbcTemplate 查询分页

    原文:http://blog.csdn.net/xiaofanku/article/details/4280128 现在进行的项目由于数据库的遗留原因(设计的不堪入目)不能用hibernate.所以用 ...

  8. spring jdbcTemplate query

    1. spring jdbcTemplate query需要实现mapRow方法 package com.cdv.apolloagent.jdbc.dao.impl; import java.sql. ...

  9. Spring JdbcTemplate的queryForList(String sql , Class<T> elementType)易错使用--转载

    原文地址: http://blog.csdn.net/will_awoke/article/details/12617383 一直用ORM,今天用JdbcTemplate再次抑郁了一次. 首先看下这个 ...

随机推荐

  1. 用junit Test Suite来组合测试

    在测试过程中,有时可能想一次性运行所有的测试类,或是选择性的运行某些测试类.这样的话我们就可以用TestSuite来统一管理我们的测试类. 比如说我现在有三个测试类:junitTest4,TestCa ...

  2. go 学习 (五):goroutine 协程

    一.goroutine 基础 定义 使用者分配足够多的任务,系统能自动帮助使用者把任务分配到 CPU 上,让这些任务尽量并发运作,此机制在Go中称作 goroutine goroutine 是 Go语 ...

  3. ssh配置基础

    1:hostname r12:R1(config)#username xxx secret ppp3:R1(config)#ip domain-name baidu.com 设置域名4:R1(conf ...

  4. WinDbg常用命令系列---显示局部变量dv

    dv (Display Local Variables) dv命令显示当前作用域中所有局部变量的名称和值. dv [Flags] [Pattern] 参数: Flags显示其他信息.可以包括以下任何区 ...

  5. CTS&&APIO2019爆零记

    如果你只好奇测试相关请跳至day 2 day 3 day 6 scoi 2019 之后 ​ 由于实力问题,省选的时候排名在三十多,显然是没有进队.不过可能是受过的打击比较多,所以还没有特别颓废,甚至连 ...

  6. 【loj2568】【APIO2016】【学习笔记 左偏树】烟花表演

    题目 一棵树,\(n\)个非叶子节点,编号为\(1-n\),\(m\)个叶子节点,编号为\(n+1-n+m\) 每条边有边权,修改边权的代价为\(|a-b|\) ; 定义一个叶子的距离为到1(根节点) ...

  7. 【转】Android系统中Fastboot和Recovery所扮演的角色。

    Android 刷机过程中 Fastboot 和 Recovery 的作用是什么? 自己在知乎的一篇回答,,现在翻出来放到博客,希望可以解答更多人的疑惑,抑或有什么理解上的错误,也望网友指出~ 今天恰 ...

  8. locust参数化(数据库取值)

    locust参数化(数据库取值) 基于上一篇参数化的梳理,本篇用另一种方法从数据库中取出这100个用户来登录 思路:在 TaskSet 中的 on_start 方法表示执行任务前的操作,可以将数据库取 ...

  9. PHP系列 | Session 存储在Redis

    默认是文件存储 修改php.ini的设置 session.save_handler = redis session.save_path = “tcp://127.0.0.1:6379″ 如果Redis ...

  10. 环境变量path的值大于1024的解决办法

    原文传送门:https://blog.csdn.net/jytxj111/article/details/43916421 1.打开Path,点击默认文本(WIN 10),将所有路径备份下来 2.新建 ...