一、Spring JDBC相关类

  1.1 DriverManagerDataSource

  DriverManagerDataSource主要包含数据库连接地址,用户名,密码。

  属性及含义如下配置所示:

<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
     <!-- 指定JDBC驱动 -->
<property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
     <!--设置数据库连接地址-->
<property name = "url" value = "jdbc:mysql://localhost:3306/spring" />
     <!-- 设置用户名和密码 -->
<property name = "username" value = "root" />
<property name = "password" value = "123456" />
</bean>

  1.2JdbcTemplate

  JdbcTemplate是实现数据库操作的核心类,其中包含一系列对数据库的操作。

  包含execute()、update()、query()等方法。

  

  既然是对数据库进行操作,那么必须知道数据库的URL,用户名密码。

  所有JdbcTemplate中应该包含DriverManagerDataSource。

  将DriverManagerDataSource配置到JdbcTemplate中:

<!--设置数据源-->
<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
<property name = "url" value = "jdbc:mysql://localhost:3306/spring" />
<property name = "username" value = "root" />
<property name = "password" value = "123456" />
</bean>
<!--在jdbcTemplate中设置数据源-->
<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>

  模板设置好了,我们就可以使用模板了。

  一般在对数据库进行具体操作的类中定义一个JdbcTemplate类型的属性,

  然后将 id = jdbcTemplate的bean注入到数据库操作类中对应的属性。

  需要导入的jar文件:

  

我们先结合jdbcTemplate中的execute() 方法来看一实例

execute(String sql)执行指定sql语句

<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd" > <!--配置数据源-->
<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
<property name = "url" value = "jdbc:mysql://localhost:3306/spring" />
<property name = "username" value = "root" />
<property name = "password" value = "123456" />
</bean>
<!--配置jdbc模板-->
<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>

测试

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; public class JDBCTemplateTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
JdbcTemplate jt = (JdbcTemplate)ac.getBean("jdbcTemplate");
jt.execute("create table account(" +
"id int primary key auto_increment," +
"username varchar(50)," +
"balance double)");
System.out.println("创建成功");
}
}

创建成功后,数据库中会多出一个account表。

本例是获取JdbcTemplate,执行了一个建表语句。

我们再来看下JdbcTemplate中的update方法。

update主要用于插入、更新、删除数据,一般会返回一个受影响的行数。

int update(String sql),执行指定语句返回受影响的行数。

int update(String sql,Object... args);执行sql语句,可以设置语句参数。

Accout.java

public class Account {
private Integer id;
private String username;
private Double balance; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
} @Override
public String toString() {
return "Account [id=" + id + ", username=" + username + ", balance=" + balance + "]";
} }

AccountDao.java (数据操作接口)

public interface AccountDao {
public int addAccount(Account account);
public int updateAccount(Account account);
public int deleteAccount(int id);
}

AccountDaoImpl.java

import org.springframework.jdbc.core.JdbcTemplate;

public class AccountDaoImpl implements AccountDao{
private JdbcTemplate jt; //此处的属性通过xml文件注入 public void setJt(JdbcTemplate jt) {
this.jt = jt;
} @Override//添加
public int addAccount(Account account) {
String sql = "insert into account(username,balance) value(?,?)";
Object[] obj = new Object[] {
account.getUsername(),
account.getBalance()
};
int num = jt.update(sql,obj);
return num;
} @Override//修改
public int updateAccount(Account account) {
String sql = "update account set username=?,balance=?,where id = ?";
Object[] obj = new Object[] {
account.getUsername(),
account.getBalance(),
account.getId()
};
int num = jt.update(sql,obj);
return num;
} @Override//删除
public int deleteAccount(int id) {
String sql = "delete from account where id = ?";
int num = jt.update(sql,id);
return num;
} }

beans.xml

<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd" > <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
<property name = "url" value = "jdbc:mysql://localhost:3306/spring" />
<property name = "username" value = "root" />
<property name = "password" value = "123456" />
</bean> <bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean> <bean id = "accountDao" class = "com.spring.db.AccountDaoImpl">
<property name="jt" ref = "jdbcTemplate"></property> <!--将jdbcTemplate注入AccountDaoImpl类中属性jt-->
</bean> </beans>

测试添加

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; public class JDBCTemplateTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
AccountDao accountDao = (AccountDaoImpl)ac.getBean("accountDao");
Account account = new Account();
account.setId(2);
account.setUsername("hcf");
account.setBalance(1000.0);
accountDao.addAccount(account);
System.out.println("添加" + accountDao.addAccount(account) + "位");
}
}

执行成功后,表中会多出一组数据。

AccountImpl执行添加方法,其内部实际上是JdbcTemplate jt执行具体的语句,

而JdbcTemplate jt是通过xml配置到AccountImpl的jt属性中的.

query方法主要用于查询,可以返回查询的结果集。

public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args)

执行指定语句,args用于设置语句参数,返回一个对象,RowMapper数据库中一行元素

与一个类之间的映射,简单的看做是将数据库一行元素填充到一个类的对象中。

类中属性名要和数据库列名相同。

rowMapper通过RowMapper的实现类BeanPropertyRowMapper(Class<T> mappedClass)构造方法构造。

这个属性确定了返回对象的具体类型。

public <T> List<T> query(String sql, RowMapper<T> rowMapper)

此方式返回的是一个结果集。

public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper)

此方法可以设置参数,同时返回结果集

在AccountDao.java中添加两个方法

public Account findAccountById(int id);
public List<Account> findAllAccounts();

在AccountDaoImpl.java中添加实现

@Override
public Account findAccountById(int id) {
String sql = "select * from account where id = ?";
//设置映射,即表中一行记录对应一个Accout对象(数据库中列名要和对象属性名一致)
RowMapper<Account> rp = new BeanPropertyRowMapper<Account>(Account.class);
return this.jt.queryForObject(sql, rp, id);
} @Override
public List<Account> findAllAccounts() {
String sql = "select * from account";
RowMapper<Account> rp = new BeanPropertyRowMapper<Account>(Account.class);
return this.jt.query(sql,rp);
}

测试:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; public class JDBCTemplateTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
AccountDao accountDao = (AccountDaoImpl)ac.getBean("accountDao");
System.out.println("all account:");
for(Account account:accountDao.findAllAccounts()) {
System.out.println(account);
}
System.out.println("---------------------------");
System.out.println("id=5:");
System.out.println(accountDao.findAccountById(5));
System.out.println("");
}
}

表中需要先有一些数据。

1.4(Spring学习笔记)Spring-JDBC基础的更多相关文章

  1. Spring学习笔记--spring+mybatis集成

    前言: 技术的发展, 真的是日新月异. 作为javaer, 都不约而同地抛弃裸写jdbc代码, 而用各种持久化框架. 从hibernate, Spring的JDBCTemplate, 到ibatis, ...

  2. Spring学习笔记一:基础概念

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6774310.html    一:Spring是什么 Spring的主要作用是作为对象的容器. 传统编程中,我们 ...

  3. spring学习笔记之---JDBC Template

    JDBC  Template(简化持久化操作) (一)创建项目 (1)Maven配置 <dependencies> <dependency> <groupId>ju ...

  4. Spring学习笔记--Spring IOC

    沿着我们上一篇的学习笔记,我们继续通过代码学习IOC这一设计思想. 6.Hello类 第一步:首先创建一个类Hello package cn.sxt.bean; public class Hello ...

  5. Spring学习笔记—Spring之旅

    1.Spring简介     Spring是一个开源框架,最早由Rod Johnson创建,并在<Expert One-on-One:J2EE Design and Development> ...

  6. Spring学习笔记--Spring配置文件和依赖注入

    Spring配置文件 1.alias:设置别名,为bean设置别名,并且可以设置多个别名; <!-- 设置别名 --> <alias name="user" al ...

  7. Spring学习笔记--Spring简介

    1.spring:给软件行业带来了春天; 2.spring的理念:spring框架的初衷是使的现有的更加实用,spring不是创造轮子(技术或框架),而是使现有的轮子更好的运转;spring本身是一个 ...

  8. Spring学习笔记——Spring中的BeanFactory与FactoryBean

    BeanFactory BeanFactory是Spring的org.springframework.beans.factory下的一个接口,是Spring IOC所遵守的基本编程规范.他的实现类有D ...

  9. Spring学习笔记——Spring依赖注入原理分析

    我们知道Spring的依赖注入有四种方式,各自是get/set方法注入.构造器注入.静态工厂方法注入.实例工厂方法注入 以下我们先分析下这几种注入方式 1.get/set方法注入 public cla ...

随机推荐

  1. 湖南大学第十四届ACM程序设计新生杯 E.Easy Problem

    E.Easy Problem Description: Zghh likes number, but he doesn't like writing problem description. So h ...

  2. WebComponents001

    Sample1: ShadowDom 隔离style,替换显示内容 <button>Hello, world!</button> <script> var host ...

  3. 【poj3420】递推式转矩阵乘法

    历史性的时刻!!! 推了一晚上!和hyc一起萌萌哒地推出来了!! 被摧残蹂躏的智商啊!!! 然而炒鸡高兴!! (请不要介意蒟蒻的内心独白..) 设a[i]为扫到第i行时的方案数. 易知,对于一行1*4 ...

  4. 【LA3487】最小割-经典模型 两种方法

    题目链接 题意:A.B两个公司要买一些资源(他们自己买的资源不会重复),一个资源只能卖给一个公司.问最大收益. simple input 部分: 54 1 //买到1就给54元 15 2 33 3 2 ...

  5. 平衡树之splay讲解

    首先来说是splay是二叉搜索树,它可以说是线段树和SBT的综合,更可以解决一些二者解决不了的问题,splay几乎所有的操作都是由splay这一操作完成的,在介绍这一操作前我们先介绍几个概念和定义 二 ...

  6. 10款最新CSS3/jQuery菜单导航插件

    这是我们在2014年收集的10款最新的CSS3 / jQuery菜单导航插件,不论从外观样式,还是功能扩展性,这些jQuery菜单一定可以满足大家的设计需求.这次我们收集的jQuery菜单,有水平 菜 ...

  7. linux shell 脚本实现tcp/upd协议通讯(重定向应用)

    linux shell 脚本实现tcp/upd协议通讯(重定向应用) http://www.cnblogs.com/chengmo/archive/2010/10/22/1858302.html

  8. python中的yield生成器详解

    #原创,转载请先联系 在学习生成器之前,必须先了解一下迭代器.因为生成器就是一种特殊的迭代器,而且生成器用起来更加优雅. 迭代器的详解可以参考我的另一篇博文:https://www.cnblogs.c ...

  9. Android局域网访问webservice以及其中的一些问题

    应老师的要求,要做个安卓app,实现备份app上的数据到服务器上的mongodb上,网上搜了下相关的实现方式.利用webservice技术,具体来说就是客户端直接调用服务器端的接口.之前从来没接触这玩 ...

  10. 腾讯云 python3+Django

    !!!注意:如果已经包含了python3.5,跳过安装3.6版本. !!!本人安装完3.6后,pip3安装的包始终没法安装到3.6目录下,只能安装到3.5目录下 1,安装python3.6(用编译的方 ...