Java进阶知识23 Spring对JDBC的支持
1、最主要的代码
Spring 配置文件(beans.xml)
<!-- 连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注册驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<!-- 数据库连接 -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
<!-- 用户 -->
<property name="user" value="root"></property>
<!-- 密码 -->
<property name="password" value="123456"></property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100"></property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="200"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="2"></property>
</bean> <!-- Spring提供的,用来代替JDBC连接数据库等操作 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- Dao层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<!-- jdbcTemplate:Spring提供的,用来 在做CRUD操作时,替代打开/获取连接等等(Connection、Statement、ResultSet),固定步骤 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
2、完整代码例子
我用到的jar包:

实例演示:
数据库建表语句
create database school; -- 创建数据库
use school; -- 使用school数据库
create table user( -- 创建user表
id int(4) primary key auto_increment,
name varchar(20) not null,
age int(4) not null
);
User 实体类
package com.shore.entity; /**
* @author DSHORE/2019-11-9
*
*/
public class User {
private Integer id;
private String name;
private Integer age; 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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
IUserDao 接口类
package com.shore.dao; import java.util.List; import com.shore.entity.User; /**
* @author DSHORE/2019-11-9
*
*/
public interface IUserDao { public void save(User user);//增
public void delete(Integer id);//删
public void update(User user);//改
public User findById(Integer id);//根据id查询
public List<User> listAll();//查询所有
}
UserDao 接口实现类
package com.shore.dao.impl; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import com.shore.dao.IUserDao;
import com.shore.entity.User; /**
* @author DSHORE/2019-11-9
*
*/
public class UserDao implements IUserDao {
//注入jdbcTemplate(Spring提供的)
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
} @Override //添加
public void save(User user) {
String sql = "insert into user(name,age) values(?,?)";
jdbcTemplate.update(sql, user.getName(),user.getAge());
} @Override //删除
public void delete(Integer id) {
jdbcTemplate.update("delete from user where id = ?", id);
} @Override //修改
public void update(User user) {
String sql = "update user set age = ? where id = ?";
jdbcTemplate.update(sql, user.getAge(), user.getId());
} @Override //根据id查询
public User findById(Integer id) {
String sql = "select * from user where id=?";
List<User> list = jdbcTemplate.query(sql, new MyResult(), id);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
} @Override //查询所有
public List<User> listAll() {
String sql = "select * from user";
List<User> list = jdbcTemplate.query(sql, new MyResult());
return list;
} //内部类 此处的作用:把findById()和listAll()的公共部分代码提出来
class MyResult implements RowMapper<User>{
@Override
// 要把每一行封装成一个User对象
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
return user;
}
}
}
Spring 配置文件(beans.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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注册驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<!-- 数据库连接 -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
<!-- 用户 -->
<property name="user" value="root"></property>
<!-- 密码 -->
<property name="password" value="root"></property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100"></property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="200"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="2"></property>
</bean> <!-- Spring提供的,用来代替JDBC连接数据库等操作 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- Dao层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<!-- jdbcTemplate:Spring提供的,用来 在做CRUD操作时,替代打开/获取连接等等(Connection、Statement、ResultSet),固定步骤 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
测试类
package com.shore.test; import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.shore.dao.IUserDao;
import com.shore.entity.User; /**
* @author DSHORE/2019-11-9
*
*/
public class MyTest { private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); @Test //添加
public void testSaveUser() {
User user = new User();
user.setName("李四");//插入两条数据:张三,18 和 李四,20
user.setAge(20);
IUserDao userDao = (IUserDao) context.getBean("userDao");
userDao.save(user);
} @Test //删除
public void testDelete() {
IUserDao userDao = (IUserDao) context.getBean("userDao");
userDao.delete(3);
} @Test //修改
public void testUpdate() {
IUserDao userDao = (IUserDao) context.getBean("userDao");
User user = userDao.findById(2);
user.setAge(26);
userDao.update(user);
} @Test //根据id查询
public void testFindById() {
IUserDao userDao = (IUserDao) context.getBean("userDao");
User user = userDao.findById(2);
System.out.println(user); //返回值:com.shore.entity.User@7df1bd98
} @Test //查询所有
public void testListAll() {
IUserDao userDao = (IUserDao) context.getBean("userDao");
List<User> users = userDao.listAll();
System.out.println(users); //返回值:[com.shore.entity.User@58ca3783, com.shore.entity.User@4402a6ff]
}
}
以上代码,均测试成功。
|
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/11827880.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |
Java进阶知识23 Spring对JDBC的支持的更多相关文章
- Java进阶知识15 Spring的基础配置详解
1.SSH各个的职责 Struts2:是web框架(管理jsp.action.actionform等).Hibernate:是ORM框架,处于持久层.Spring:是一个容器框架,用于配置bean,并 ...
- Java进阶知识20 Spring的代理模式
本文知识点(目录): 1.概念 2.代理模式 2.1.静态代理 2.2.动态代理 2.3.Cglib子类代理 1.概念 1.工厂模式 2. 单例模式 代理(Proxy ...
- Java进阶知识25 Spring与Hibernate整合到一起
1.概述 1.1.Spring与Hibernate整合关键点 1) Hibernate的SessionFactory对象交给Spring创建. 2) hibernate事务交给spring的声明 ...
- Java进阶知识24 Spring的事务管理(事务回滚)
1.事务控制概述 1.1.编程式事务控制 自己手动控制事务,就叫做编程式事务控制. Jdbc代码: connection.setAutoCommit(false); ...
- Java进阶知识17 Spring Bean对象的创建细节和创建方式
本文知识点(目录): 1.创建细节 1) 对象创建: 单例/多例 2) 什么时候创建? 3)是否延迟创建(懒加载) 4) 创建对象之后, ...
- Java进阶知识22 Spring execution 切入点表达式
1.概述 切入点(execution ):可以对指定的方法进行拦截,从而给指定的类生成代理对象.(拦截谁,就是在谁那里切入指定的程序/方法) 格式: execution(modifiers-pat ...
- Java进阶知识21 Spring的AOP编程
1.概述 Aop:(Aspect Oriented Programming)面向切面编程 功能: 让关注点代码与业务代码分离! 关注点:重复代码就叫做关注点:切面: 关注点形成的类, ...
- Java进阶知识18 Spring对象依赖关系的几种写法
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- Java进阶知识16 Spring创建IOC容器的两种方式
1.直接得到 IOC 容器对象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app ...
随机推荐
- List 集合 使用 remove 踩得坑
不要在 foreach 循环里进行元素的 remove/add 操作.remove 元素请使用 Iterator方式,如果并发操作,需要对 Iterator 对象加锁. 正确例子: Iterato ...
- 给初学PHP的学习线路和建议
直入主题 1.熟悉HTML/CSS/JS等网页基本元素,完成阶段可自行制作简单的网页,对元素属性相对熟悉. 2.理解动态语言的概念和运做机制,熟悉基本的PHP语法. 3.学习如何将PHP与HTML结 ...
- (十三)Activitivi5之流程控制网关:并行
一.概念 所谓排他网关 顾名思义 执行到该网关,会有多条线路同时并行执行,当都执行完才继续执行后面的: 二. 案例 此时当“学生请假”任务节点完成之后,如下图此时有两个任务,必须等到两个任务都完成才会 ...
- (四)lucene之文本域加权
一.前言 1.1 应用场景 有时在搜索的时候,会根据需要的不同,对不同的关键值或者不同的关键索引分配不同的权值,让权值高的内容更容易被用户搜索出来,而且排在前面. 为索引域添加权是再创建索引之前,把索 ...
- 在Angular中使用$ compile
转载自:http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx 在AngularJS中创建一 ...
- http协议与soap协议之间的区别
http是标准超文本传输协议.使用对参数进行编码并将参数作为键值对传递,还使用关联的请求语义.每个协议都包含一系列HTTP请求标头及其他一些信息,定义客户端向服务器请求哪些内容,服务器用一系列HTTP ...
- Python函数知识点总结
1.函数的定义2.如何定义一个函数以及函数语法3.函数的调用4.函数的参数(形参,实参)以及参数的传递5.函数的返回值6.变量的作用域7.匿名函数8.嵌套函数和闭包9.装饰器10.函数思维导图 1.函 ...
- docker系列七之Dockerfile
Dockerfile 一. Dockerfile是什么 Dockerfile是docker中镜像文件的的描述文件,说的直白点就是镜像文件到底是由什么东西一步步构成的.例如我们在淘宝上买了一件商品, ...
- 字符串slice、substring、substr
1.slice() 可以为负数,如果起始位置为负数,则从字符串最后一位向前找对应位数并且向后取结束位置,如果为正整数则从前往后取起始位置到结束位置. 2.substring() 只能非负整数,截取起始 ...
- Cryptography -- 密码学
Introduction to Cryptography Cryptography enables you to store sensitive information or transmit it ...