`
hunray
  • 浏览: 219246 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

【转】spring数据源的注入.JDBC模版管理

    博客分类:
  • Java
阅读更多

对于不同的数据库连接来源需求,spring提供了javax.sql.DataSource注入,更换数据来源只要在Bean定义中修改配置,而不用修改任何一行代码。
         应不同的系统,可能使用不同的数据来源,例如:jdbc、连接池、或是JNDI等等,资料变更是底层的行为,不应影响到上层的业务逻辑。
例子:
<beans>
       <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
           <property name="driverClassName">
               <value>com.mysql.jdbc.Driver</value>
           </property>
           <property name="url">
               <value>jdbc:mysql://localhost:3306/demo</value>
           </property>
           <property name="username">
               <value>caterpillar</value>
           </property>
           <property name="password">
               <value>123456</value>
           </property>
       </bean>
         <bean id="userDao" class="onlyfun.caterpillar.UserDao">
            <property name="dataSource">
               <ref bean="datasource"/>
            </property>
      </bean>
</beans>
其中"driverClassName"、"url"、"username"、"password"四個屬性分別用來設定JDBC驅動程式類別、資料庫 URL協定、使用者名稱、密碼,而DriverManagerDataSource继承了javax.sql.DataSource.
注意:
(1)、该例子使用的是简单的jdbc连接,如果应用到工程,必须使用连接池,这时只要更换class属性为class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
(2)、如果采用的是JNDI连接,可以这么设定:
<bean id="dataSource"
      class="org.springframework.indi.JndiObjectFactoryBean">
      <property name="jndiName">
         <value>jdbc/demo</value>
        </property>
</bean>
Spring学习笔记JDBC模版管理
对于Spring应用,Spring 提供了一个更好的数据持久化的框架,Spring让持久层的类UserDao继承 org.springframework.jdbc.core.JdbcTemplate这个封装了jdbc操作的类,要建立JdbcTemplate的实例,必须要有一个DataSource物件作为建构时的物件.
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
例子(1):-----取得模版
package onlyfun.caterpillar;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDAO implements IUserDAO {
      private JdbcTemplate jdbcTemplate;
      public void setDataSource(DataSource dataSource) {
          jdbcTemplate = new JdbcTemplate(dataSource);
      }
          return null;
      }
}
例子(2):-----update操作(同样的操作适用于update、insert、delete)
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate
.update(
"UPDATE user SET age = ? WHERE id = ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatementSetter ps)
throws SQLException {
ps.setInt(1, 18);
ps.setString(2, "erica");
}
}
);
第一个用于创建PreparedStatement的SQL。第二个参数是为PreparedStatement设定参数的
PreparedStatementSetter
注意:我们还可以通过JdbcTemplate.call方法调用存储过程.
编程式的事务管理:我们可以使用 org.springframework.jdbc.datasource.DataSourceTransactionManager(platformTransactionManager 的一个实现)作为我们的事务管理员,我们在Bean定义中配置,并将DataSource注入给它。
配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/TestDB</value>
           </property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value></value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="userDAO" class="onlyfun.caterpillar.UserDAO">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
</bean>
</beans>

DAO操作类:

package onlyfun.caterpillar;
import javax.sql.DataSource;
import org.springframework.jdbc.core.*;
import org.springframework.transaction.*;
import org.springframework.transaction.support.*;
import org.springframework.dao.*;
public class UserDAO {
private DataSource dataSource;
private PlatformTransactionManager transactionManager;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void insertUser(User user) {

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update("INSERT INTO USER VALUES('Spring008', 'caterpillar', 'M', 29)");
jdbcTemplate.update("INSERT INTO USER VALUES('Spring009', 'momor', 'F', 26)");
jdbcTemplate.update("INSERT INTO USER VALUES('Spring010, 'beckyday', 'F', 35)");
} catch (DataAccessException ex) {
transactionManager.rollback(status); // 也可以執行status.setRollbackOnly();
        throw ex;
}
transactionManager.commit(status);


}
}

分享到:
评论

相关推荐

    Spring-Reference_zh_CN(Spring中文参考手册)

    配置子报表数据源 14.7.5. 配置Exporter的参数 15. 集成其它Web框架 15.1. 简介 15.2. 通用配置 15.3. JavaServer Faces 15.3.1. DelegatingVariableResolver 15.3.2. FacesContextUtils 15.4. Struts 15.4.1. ...

    Spring 2.0 开发参考手册

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. ...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    spring chm文档

    Spring Framework 开发参考手册 Rod Johnson Juergen Hoeller Alef Arendsen Colin Sampaleanu Rob Harrop Thomas Risberg Darren Davison Dmitriy Kopylenko Mark Pollack Thierry Templier Erwin ...

    springboot参考指南

    Spring Beans和依赖注入 vi. 18. 使用@SpringBootApplication注解 vii. 19. 运行应用程序 i. 19.1. 从IDE中运行 ii. 19.2. 作为一个打包后的应用运行 iii. 19.3. 使用Maven插件运行 iv. 19.4. 使用Gradle插件运行 v...

    Spring.3.x企业应用开发实战(完整版).part2

    8.4.3 Spring的数据源实现类 8.5 小结 第9章 Spring的事务管理 9.1 数据库事务基础知识 9.1.1 何为数据库事务 9.1.2 数据并发的问题 9.1.3 数据库锁机制 9.1.4 事务隔离级别 9.1.5 JDBC对事务支持 9.2 ThreadLocal...

    Spring in Action(第二版 中文高清版).part2

    5.2.3 基于JDBC驱动的数据源 5.3 在Spring里使用JDBC 5.3.1 处理失控的JDBC代码 5.3.2 使用JDBC模板 5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 ...

    Spring in Action(第二版 中文高清版).part1

    5.2.3 基于JDBC驱动的数据源 5.3 在Spring里使用JDBC 5.3.1 处理失控的JDBC代码 5.3.2 使用JDBC模板 5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 ...

    ssh(structs,spring,hibernate)框架中的上传下载

     第3~9行定义了一个数据源,其实现类是apache的BasicDataSource,第11~25行定义了Hibernate的会话工厂,会话工厂类用Spring提供的LocalSessionFactoryBean维护,它注入了数据源和资源映射文件,此外还通过一些键值...

    Spring3.x企业应用开发实战(完整版) part1

    8.4.3 Spring的数据源实现类 8.5 小结 第9章 Spring的事务管理 9.1 数据库事务基础知识 9.1.1 何为数据库事务 9.1.2 数据并发的问题 9.1.3 数据库锁机制 9.1.4 事务隔离级别 9.1.5 JDBC对事务支持 9.2 ThreadLocal...

    Spring攻略(第二版 中文高清版).part1

    7.1 用Spring Web Flow管理简单的UI流程 238 7.1.1 问题 238 7.1.2 解决方案 239 7.1.3 工作原理 239 7.2 用不同状态类型建立Web流程模型 246 7.2.1 问题 246 7.2.2 解决方案 246 7.2.3 工作原理 ...

    Spring攻略(第二版 中文高清版).part2

    7.1 用Spring Web Flow管理简单的UI流程 238 7.1.1 问题 238 7.1.2 解决方案 239 7.1.3 工作原理 239 7.2 用不同状态类型建立Web流程模型 246 7.2.1 问题 246 7.2.2 解决方案 246 7.2.3 工作原理 ...

    Spring in Action(第2版)中文版

    5.2.3基于jdbc驱动的数据源 5.3在spring里使用jdbc 5.3.1处理失控的jdbc代码 5.3.2使用jdbc模板 5.3.3使用spring对jdbc的dao支持类 5.4在spring里集成hibernate 5.4.1选择hibernate的版本 5.4.2使用hibernate...

    spring boot集成demo大全.zip

    ElasticSearch(`基本操作和高级查询`)、Async(`异步任务`)、集成Dubbo(`采用官方的starter`)、MongoDB(`文档数据库`)、neo4j(`图数据库`)、docker(`容器化`)、`JPA多数据源`、`Mybatis多数据源`、`代码生成器`、Gray...

    基于springboot的一个IT人才招聘网站系统源码+数据库+部署文档,公司可以发布岗位需求,求职者查找岗位并递交简历等

    2.1 数据库数据源部署 src/main/resources/application.yaml 配置文件: 配置 MySQL 数据库 datasource spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3307/...

    spring-boot-demo_xkcoding.tar.gz

    ElasticSearch(基本操作和高级查询)、Async(异步任务)、集成Dubbo(采用官方的starter)、MongoDB(文档数据库)、neo4j(图数据库)、docker(容器化)、JPA多数据源、Mybatis多数据源、代码生成器、GrayLog(日志收集)、...

    spring boot 实践学习案例,与其它组件整合

    其中,每个版本都有其对应的多数据源解决方案。 - springboot-caches - Spring Boot 缓存,包括redis、ehcache、spring-cache、memcached、使用redis实现session共享 等。 - springboot-templates - Spring ...

    JSP+SQL房屋租赁管理信息系统JDBC(源代码+论文+答辩PPT).zip.tar.gz

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot...

    单点登录源码

    ├── zheng-admin -- 后台管理模板 ├── zheng-ui -- 前台thymeleaf模板[端口:1000] ├── zheng-config -- 配置中心[端口:1001] ├── zheng-upms -- 用户权限管理系统 | ├── zheng-upms-common -- upms...

Global site tag (gtag.js) - Google Analytics