Spring框架基础(中)
- Spring对不同持久化技术进行支持
- JDBC
- 导入spring-jdbc-4.3.5.RELEASE.jar、spring-tx-4.3.5.RELEASE.jar
- 创建对象,设置数据库信息
- 创建jdbcTemplate对象,设置数据源
- 调用jdbcTemplate对象里面对方法实现操作
public class TestDao { /**
* 添加指定数据表的数据
*/
public void insertUser() { try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句
String sql = "insert into user (username,password,email,root,register_time) values (?,?,?,?,?) ";
//
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
int rows = jdbcTemplate.update(sql,"rabbit","rabbit","rabbit@qq.com",1,"2019-3-2"); System.out.println("rows="+rows);
} catch (IOException e) {
e.printStackTrace();
} } /**
* 更新指定数据表的数据
*/
public void updateUser() { try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句 String sql = "update user set phone = ? where username = ?";
//
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); int rows = jdbcTemplate.update(sql,"13812392132","rabbit");
System.out.println("rows=" + rows);
} catch (IOException e) {
e.printStackTrace();
} }
/**
* 查询全部数据
*/
public void selectAllUser() { try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句 String sql = "select * from user";
//
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
System.out.println("maps=" + maps);
} catch (IOException e) {
e.printStackTrace();
} }
/**
* 删除指定数据
*/
public void deleteUser() { try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句 String sql = "delete from user where username = ?";
//
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource); int row = jdbcTemplate.update(sql, "rabbit");
System.out.println("row=" + row);
} catch (IOException e) {
e.printStackTrace();
} } /**
* 查询指定数据表的记录数
*/
public void selectCountUser() {
try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句 String sql = "select count(*) from user";
//
JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);
//第一个参数sql语句,第二个参数返回的数据类型
Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println("count=" + count);
} catch (IOException e) {
e.printStackTrace();
} } public void selectUser();() { try {
//导入配置文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
//
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setJdbcUrl(driver);
driverManagerDataSource.setJdbcUrl(url);
driverManagerDataSource.setUser(username);
driverManagerDataSource.setPassword(password);
//数据库语句 String sql = "select * from user where username = ?"; User user = jdbcTemplate.queryForObject(sql, new NewRowMapper(), "rabbit");
JSONObject jsonObject = JSONObject.fromObject(user);
System.out.println(jsonObject + "");
} catch (IOException e) {
e.printStackTrace();
} } /**
* 处理查询结果集
*/
class NewRowMapper implements RowMapper<User> { @Override
public User mapRow(ResultSet resultSet, int i) throws SQLException { try {
Class<?> newClass = Class.forName("cn.muriel.auto.pojo.User");
Object o = newClass.newInstance();
for (int j = 1; j <= resultSet.getMetaData().getColumnCount(); j++) {
String name = resultSet.getMetaData().getColumnName(j);
String type = resultSet.getMetaData().getColumnTypeName(j);
//针对只有一次_的情况,多次则可用递归
if (name.contains("_")) {
int position = name.indexOf("_");
String smailChar = name.substring(position + 1, position + 2).toUpperCase();
name = name.substring(0, position) + smailChar + name.substring(position + 2, name.length());
}
Field declaredField = newClass.getDeclaredField(name);
if (declaredField != null) {
declaredField.setAccessible(true);
if (type.equals("INT"))
declaredField.set(o, resultSet.getInt(name));
else if (type.equals("VARCHAR"))
declaredField.set(o, resultSet.getString(name));
} }
return (User) o; } catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} return null;
}
} } /**
* 测试代码
*/
public static void main(String[] args) { Test01 test01 = (Test01) applicationContext.getBean("test01");
test01.test01();*/ TestDao dao = new TestDao();
dao.insertUser();
dao.updateUser();
dao.selectAllUser();
dao.selectUser();
dao.selectCountUser();
} - spring配置c3p0连接池
- 导入mchange-commons-java-0.2.11.jar、c3p0-0.9.5.2.jar
- 连接连接池
- 代码实现
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
try {
properties.load(inputStream);
//获取参数
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(username);
comboPooledDataSource.setPassword(password);
} catch (IOException e) {
e.printStackTrace();
} catch (PropertyVetoException e) {
e.printStackTrace();
} - 注入实现
<?xml version="1.0" encoding="UTF-8" ?>
<!--
http://www.springframework.org/schema/context/spring-context.xsd:用于注解的约束
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自动注入
<context:component-scan base-package="cn.muriel.auto.dao"/> --> <context:property-placeholder location="db.properties"/>
<!-- 配置注入 -->
<bean id="userDao" class="cn.muriel.auto.dao.UserDao"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean> <bean id="testDao" class="cn.muriel.auto.dao.TestDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean> </beans>
- 代码实现
- Hibernate
- Ibatis(MyBatis)
- JPA
- JDBC
- Spring的事务管理
- 什么是事务
- 事务的特性
- 不考虑隔离性产生读问题
- 解决读问题
- 设置隔离级别
- spring事务管理两种方式
- 编程式事务管理
- 声明式事务管理
- 基于xml配置文件实现
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务增强 -->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<!-- 做事务操作 -->
<tx:attributes>
<!--
设置进行事务操作的方法匹配规则
name:匹配名字
propagation:默认。
-->
<tx:method name="insert*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut id="pointcut1" expression="* (cn.muriel.auto.service.TestService.*)(..)"/>
<!-- 切面 -->
<aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/>
</aop:config> - 基于注解实现
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/> /**
* 使用事务的方法所在类上面添加注解
*/
@Transactional
public class TestService { }
- 基于xml配置文件实现
- spring事务管理高层抽象主要包括3个接口
- PlatformTransactionManager(事务管理器)
- spring针对不同的dao层框架,提供接口不同的实现类
- 首先都要配置事务管理器
- TransactionDefinition(事务定义信息(隔离、传播、超时、只读))
- TransactionStatus(事务具体运行状态)
- PlatformTransactionManager(事务管理器)
Spring框架基础(中)的更多相关文章
- Spring框架基础2
Spring框架基础2 测试Spring的AOP思想和注解的使用 导包(在前面的基础上添加) SpringAOP名词解释 AOP编程思想:横向重复代码,纵向抽取:就是说多个地方重复的代码可以抽取出来公 ...
- Spring学习指南-第二章-Spring框架基础(完)
第二章 Spring框架基础 面向接口编程的设计方法 在上一章中,我们看到了一个依赖于其他类的POJO类包含了对其依赖项的具体类的引用.例如,FixedDepositController 类包含 ...
- 4-1 Spring框架基础知识
Spring框架基础知识 1.Spring 框架作用 主要解决了创建对象和管理对象的问题. 自动装配机制 2.Spring 框架 (Spring容器,JavaBean容器,Bean容器,Spring容 ...
- Spring框架基础知识
本人博客文章网址:https://www.peretang.com/basic-knowledge-of-spring-framework/ Spring框架简介 Spring , 一个开源的框架 , ...
- Spring框架基础
1 Spring框架 1.1 Spring的基本概念 是一个轻量级的框架,提供基础的开发包,包括消息.web通讯.数据库.大数据.授权.手机应用.session管理 ...
- Spring 框架基础(04):AOP切面编程概念,几种实现方式演示
本文源码:GitHub·点这里 || GitEE·点这里 一.AOP基础简介 1.切面编程简介 AOP全称:Aspect Oriented Programming,面向切面编程.通过预编译方式和运行期 ...
- Spring框架基础解析
Spring是一个轻量级的.非侵入式的容器框架:对Bean对象的生命周期进行管理. Spring框架的核心:IOC(控制反转).DI(依赖注入).AOP(面向切面编程). (1) IOC:控制反转. ...
- Spring 框架基础(06):Mvc架构模式简介,执行流程详解
本文源码:GitHub·点这里 || GitEE·点这里 一.SpringMvc框架简介 1.Mvc设计理念 MVC是一种软件设计典范,用一种业务逻辑.数据.界面显示分离的方法组织代码,将业务逻辑聚集 ...
- Spring 框架基础(03):核心思想 IOC 说明,案例演示
本文源码:GitHub·点这里 || GitEE·点这里 一.IOC控制反转 1.IOC容器思想 Java系统中对象耦合关系十分复杂,系统的各模块之间依赖,微服务模块之间的相互调用请求,都是这个道理. ...
- Spring 框架基础(02):Bean的生命周期,作用域,装配总结
本文源码:GitHub·点这里 || GitEE·点这里 一.装配方式 Bean的概念:Spring框架管理的应用程序中,由Spring容器负责创建,装配,设置属性,进而管理整个生命周期的对象,称为B ...
随机推荐
- DevExpress XtraTabbedMdiManager删除Page
DevExpress XtraTabbedMdiManager删除Page 时,xtraTabbedMdiManager1.Pages.Remove()是没用的. 正确的应该是xtraTabbedMd ...
- 使用AOP实现方法执行时间和自定义注解
环境:IDEA2018+JDK1.8+SpringBoot 第一步:在pom文件中引入依赖(度娘有很多(*^▽^*)): <!--引入AOP的依赖--><dependency> ...
- IOS - 上APPSTORE为何因IPv6被拒?
http://blog.csdn.net/wanglixin1999/article/details/52182001
- [译]async/await中阻塞死锁
这篇博文主要是讲解在async/await中使用阻塞式代码导致死锁的问题,以及如何避免出现这种死锁.内容主要是从作者Stephen Cleary的两篇博文中翻译过来. 原文1:Don'tBlock o ...
- Android 实现卡片翻转的动画(翻牌动画)
Android 实现卡片翻转的动画(翻牌动画) 需求描述 点击卡片,卡片翻转过来显示内容. 点击左边的卡片,将卡片翻转显示右边的图片结果. 功能实现 因为要翻转所以使用动画来完成翻转的动画.动画分为两 ...
- [Swift]LeetCode354. 俄罗斯套娃信封问题 | Russian Doll Envelopes
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envel ...
- [Swift]LeetCode453. 最小移动次数使数组元素相等 | Minimum Moves to Equal Array Elements
Given a non-empty integer array of size n, find the minimum number of moves required to make all arr ...
- GenerationType四中类型
https://blog.csdn.net/u011781521/article/details/72210980 JPA提供的四种标准用法为TABLE,SEQUENCE,IDENTITY,AUTO. ...
- Python内置函数(62)——sum
英文文档: sum(iterable[, start]) Sums start and the items of an iterable from left to right and returns ...
- Python内置函数(12)——compile
英文文档: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) Compile the source i ...