一个spring jdbc实例
一、使用示例
(1)springJdbcContext.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:context="http://www.springframework.org/schema/context"
- 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-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
- <description>springApp</description>
- <!-- dataSource for MySQL -->
- <bean id="dataSource"
- class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close">
- <property name="driverClassName"
- value="com.mysql.jdbc.Driver" />
- <property name="url"
- value="jdbc:mysql://localhost:3306/springapp" />
- <property name="username" value="root" />
- <property name="password" value="****" />
- </bean>
- <bean id = "TransactionManager"
- class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name = "dataSource" ref="dataSource"/>
- </bean>
- <!--1:配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去-->
- <bean id = "jdbcTemplate"
- class = "org.springframework.jdbc.core.JdbcTemplate">
- <property name = "dataSource" ref="dataSource"/>
- </bean>
- <bean id = "actorJdbcTemplateDao"
- class = "com.logcd.bo.dao.impl.ActorJdbcTemplateDaoImpl">
- <property name="jdbcTemplate" ref="jdbcTemplate"/>
- </bean>
- <!--2:将共享的DataSource实例注入到DAO中,JdbcTemplate实例在DataSource的setter方法中被创建-->
- <bean id = "actorEventDao"
- class = "com.logcd.bo.dao.impl.ActorEventDaoImpl">
- <property name = "dataSource" ref="dataSource"/>
- </bean>
- <!--利用了拦截器的原理。-->
- <bean id="transactionInterceptor"
- class="org.springframework.transaction.interceptor.TransactionInterceptor">
- <property name="transactionManager">
- <ref bean="transactionManager" />
- </property>
- <!-- 配置事务属性 -->
- <property name="transactionAttributes">
- <props>
- <prop key="delete*">PROPAGATION_REQUIRED</prop>
- <prop key="operate*">PROPAGATION_REQUIRED,-Exception</prop>
- <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
- <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
- <prop key="save*">PROPAGATION_REQUIRED</prop>
- <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
- </props>
- </property>
- </bean>
- <bean id="txProxy"
- class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
- <property name="beanNames">
- <list>
- <value>*Dao*</value><!--只是为了测试,一般为service-->
- </list>
- </property>
- <property name="interceptorNames">
- <list>
- <value>transactionInterceptor</value>
- </list>
- </property>
- </bean>
- </beans>
(2)接口:(以第二种方式定义DAO)
- package com.logcd.bo.dao;
- import java.util.List;
- import org.springframework.jdbc.support.KeyHolder;
- import com.logcd.bo.Actor;
- public interface ActorEventDao {
- /**
- * 根据SQL建表
- * @param sql
- */
- public void createTableBySQL(String sql);
- /**
- * 统计firstName相同的总数
- * @param firstName
- * @return
- */
- public int findCountOfActorsByFirstName(String firstName);
- /**
- * 插入记录并返回自动生成的主键Id
- * @param ps
- * @return
- */
- public KeyHolder insertActor(final Actor actor);
- /**
- * 用SimpleJdbcInsert插入一条记录:mysql测试成功
- */
- public long inserOneActor(Actor actor);
- /**
- * 插入/更新/删除数据
- * @param sql 有参数语句
- * @param obj 参数值数组
- */
- public int operateActor(String sql,Object[] obj);
- /**
- * 根据SQL查询记录总数
- * @param sql
- * @return
- */
- public int findRowCountBySQL(String sql);
- /**
- * 根据Id查找指定对象
- * @param id
- * @return
- */
- public Actor findActorById(long id);
- /**
- * 根据Id查找指定对象
- * @param id
- * @return
- */
- public Actor findActorByIdSimple(long id);
- /**
- * 返回所有对象
- * @return
- */
- public List findAllActors();
- /**
- * 批量更新
- * @param actors
- * @return
- */
- public int[] updateBatchActors(final List actors);
- /**
- * 批量更新
- * @param actors
- * @return
- */
- public int[] updateBatchActorsSimple(final List<Actor> actors);
- }
(3)接口实现
- package com.logcd.bo.dao.impl;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
- import javax.sql.DataSource;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.PreparedStatementCreator;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.jdbc.support.GeneratedKeyHolder;
- import org.springframework.jdbc.support.KeyHolder;
- import com.logcd.bo.Actor;
- import com.logcd.bo.dao.ActorEventDao;
- public class ActorEventDaoImpl implements ActorEventDao{
- private JdbcTemplate jdbcTemplate;
- //NamedParameterJdbcTemplate对JdbcTemplate封装,增加了命名参数特性
- private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
- //SimpleJdbcTemplate对JdbcTemplate封装,某些特性要在java5以上才工作
- private SimpleJdbcTemplate simpleJdbcTemplate;
- //简化插入数据操作
- private SimpleJdbcInsert inserActor;
- public void setDataSource(DataSource dataSource){
- this.jdbcTemplate = new JdbcTemplate(dataSource);
- this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
- this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
- this.inserActor = new SimpleJdbcInsert(dataSource)
- .withTableName("actors")
- .usingColumns("first_name","last_name")//插入这些字段
- .usingGeneratedKeyColumns("id");//带回生成的id
- }
- /**
- * 用SimpleJdbcInsert插入一条记录
- */
- public long inserOneActor(Actor actor){
- Map<String,Object> parameters = new HashMap<String,Object>();
- parameters.put("first_name",actor.getFirstName());
- parameters.put("last_name",actor.getLastName());
- return inserActor.executeAndReturnKey(parameters).longValue();
- }
- /**
- * 统计firstName相同的总数
- * @param firstName
- * @return
- */
- public int findCountOfActorsByFirstName(String firstName){
- String sql="select count(0) from actors where first_name = :first_name";
- SqlParameterSource namedParameters = new MapSqlParameterSource("first_name",firstName);
- //Map namedParameter = Collections.singletonMap("first_name",firstName);
- //还有一种Bean封装的方式
- //SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);
- return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
- }
- /**
- * 根据SQL建表
- * @param sql
- */
- public void createTableBySQL(String sql) {
- this.jdbcTemplate.execute(sql);
- }
- /**
- * 插入记录并返回自动生成的主键Id(MySQL中不行,Oracle可以)
- * @param ps
- * @return
- */
- public KeyHolder insertActor(final Actor actor){
- final String addSql = "insert into actors(first_name,last_name) values (?,?)";
- KeyHolder keyHolder = new GeneratedKeyHolder();
- this.jdbcTemplate.update(new PreparedStatementCreator(){
- public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
- PreparedStatement ps =
- conn.prepareStatement(addSql, new String[]{"id"});//返回id
- ps.setString(1, actor.getFirstName());
- ps.setString(2, actor.getLastName());
- return ps;
- }
- });
- System.out.println(keyHolder.getKey());
- return keyHolder;
- }
- /**
- * 插入/更新/删除数据
- * @param sql 有参数语句
- * @param obj 参数值数组
- */
- public int operateActor(String sql,Object[] obj){
- return this.jdbcTemplate.update(sql, obj);
- }
- /**
- * 根据SQL查询记录总数
- * @param sql
- * @return
- */
- public int findRowCountBySQL(String sql){
- return this.jdbcTemplate.queryForInt(sql);
- }
- /**
- * 根据Id查找指定对象
- * @param id
- * @return
- */
- public Actor findActorById(long id){
- Actor actor = (Actor) this.jdbcTemplate.queryForObject(
- "select id,first_name,last_name from actors where id = ?",
- new Object[]{new Long(id)},
- new RowMapper(){
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- Actor act = new Actor();
- act.setId(rs.getLong("id"));
- act.setFirstName(rs.getString("first_name"));
- act.setLastName(rs.getString("last_Name"));
- return act;
- }
- });
- return actor;
- }
- /**
- * 根据Id查找指定对象
- * @param id
- * @return
- */
- public Actor findActorByIdSimple(long id){
- String sql = "select id,first_name,last_name from actors where id = ?";
- ParameterizedRowMapper<Actor> mapper = new ParameterizedRowMapper<Actor>(){
- //notice the return type with respect to java 5 covariant return types
- public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
- Actor act = new Actor();
- act.setId(rs.getLong("id"));
- act.setFirstName(rs.getString("first_name"));
- act.setLastName(rs.getString("last_Name"));
- return act;
- }
- };
- return this.simpleJdbcTemplate.queryForObject(sql, mapper, id);
- }
- /**
- * 返回所有对象
- * @return
- */
- public List findAllActors(){
- return this.jdbcTemplate.query(
- "select id,first_name,last_name from actors",
- new ActorMapper());
- }
- /**
- * 定义一个静态内部类,在Dao的方法中被共享
- * @author logcd
- */
- private static final class ActorMapper implements RowMapper{
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- Actor act = new Actor();
- act.setId(rs.getLong("id"));
- act.setFirstName(rs.getString("first_name"));
- act.setLastName(rs.getString("last_Name"));
- return act;
- }
- }
- }
- /**
- * 批量更新
- * @param actors
- * @return
- */
- public int[] updateBatchActors(final List actors){
- int[] updateCounts =this.jdbcTemplate.batchUpdate(
- "update actors set first_name = ?, last_name = ? where id =? ",
- new BatchPreparedStatementSetter(){
- public int getBatchSize() {
- return actors.size();
- }
- public void setValues(PreparedStatement ps, int i) throws SQLException {
- ps.setString(1, ((Actor)actors.get(i)).getFirstName());
- ps.setString(2, ((Actor)actors.get(i)).getLastName());
- ps.setLong(3, ((Actor)actors.get(i)).getId());
- }
- });
- return updateCounts;
- }
- /**
- * 批量更新
- * @param actors
- * @return
- */
- public int[] updateBatchActorsSimple(final List<Actor> actors){
- //如果对象数组与占位符出现位置一一对应
- //SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(actors.toArray());
- List<Object[]> batch = new ArrayList<Object[]>();
- for(Actor actor:actors){
- Object[] values = new Object[]{//注意顺序
- actor.getFirstName(),
- actor.getLastName(),
- actor.getId()};
- batch.add(values);
- }
- int[] updateCounts = this.simpleJdbcTemplate.batchUpdate(
- "update actors set first_name = ?, last_name = ? where id =? ",
- batch);
- return updateCounts;
- }
(4)测试
- /**
- *
- */
- package com.logcd.test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.jdbc.support.KeyHolder;
- import com.logcd.bo.Actor;
- import com.logcd.bo.dao.ActorEventDao;
- import com.logcd.bo.dao.ActorJdbcTemplateDao;
- import junit.framework.TestCase;
- /**
- * @author logcd
- */
- public class SpringJdbcTest extends TestCase {
- private ActorEventDao actorEventDao;
- private ActorJdbcTemplateDao actorJdbcTemplateDao;
- protected void setUp() throws Exception {
- super.setUp();
- ApplicationContext context = new ClassPathXmlApplicationContext("springJdbcContext.xml");
- actorEventDao = (ActorEventDao)context.getBean("actorEventDao");
- actorJdbcTemplateDao = (ActorJdbcTemplateDao)context.getBean("actorJdbcTemplateDao");
- }
- protected void tearDown() throws Exception {
- super.tearDown();
- }
- public void testActorEventDao(){
- String creatSql = "create table ACTORS(" +
- "ID int not null auto_increment," +
- "FIRST_NAME varchar(15)," +
- "LAST_NAME varchar(15)," +
- "primary key (ID)" +
- ");" ;
- //建表
- actorEventDao.createTableBySQL(creatSql);
- String addSql = "insert into actors(first_name,last_name) values(?,?);";
- Object[] obj = new Object[]{"wang","jinming"};
- //新增
- System.out.println(actorEventDao.operateActor(addSql, obj));
- String countSql = "select count(0) from actors";
- System.out.println("Count:"+actorEventDao.findRowCountBySQL(countSql));
- System.out.println("Count:"+actorJdbcTemplateDao.findRowCountBySQL(countSql));
- //根据id查找
- Actor actor = actorEventDao.findActorById(1);
- System.out.println("id:"+actor.getId()+" first_name:"+actor.getFirstName()+" last_name:"+actor.getLastName());
- //输出所有
- for(Object o:actorEventDao.findAllActors()){
- Actor act = (Actor) o;
- System.out.println("id:"+act.getId()+" first_name:"+act.getFirstName()+" last_name:"+act.getLastName());
- }
- Actor newAct=new Actor();
- newAct.setFirstName("jin");
- newAct.setLastName("ming");
- KeyHolder keyHold =actorEventDao.insertActor(newAct);
- System.out.println(keyHold.getKey());//mysql得不到id
- List<Actor> list = new ArrayList<Actor>();
- for(Object o:actorEventDao.findAllActors()){
- Actor act = (Actor) o;
- System.out.println("id:"+act.getId()+" first_name:"+act.getFirstName()+" last_name:"+act.getLastName());
- act.setLastName("www");
- list.add(act);
- }
- actorEventDao.batchUpdateActors(list);
- for(Object o:actorEventDao.findAllActors()){
- Actor act = (Actor) o;
- System.out.println("id:"+act.getId()+" first_name:"+act.getFirstName()+" last_name:"+act.getLastName());
- }
- }
- }
二、关于操作Blob和Clob问题
spring定义了一个以统一的方式操作各种数据库的Lob类型数据的LobCreator(保存的时候用),同时提供了一个LobHandler为操作二进制字段和大文本字段提供统一接口访问。
(1)配置文件
- <bean id="nativeJdbcExtractor"
- class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"
- lazy-init="true"/>
- <bean id="lobHandler"
- class="org.springframework.jdbc.support.lob.OracleLobHandler"
- lazy-init="true"
- p:nativeJdbcExtractor-ref="nativeJdbcExtractor"/>
- <bean id="defaultLobHandler"
- class="org.springframework.jdbc.support.lob.DefaultLobHandler"
- lazy-init="true" />
- <bean id="jdbcTemplate"
- class="org.springframework.jdbc.core.JdbcTemplate"
- p:dataSource-ref="appDS"
- p:nativeJdbcExtractor-ref="nativeJdbcExtractor"/>
- <bean id="txMangager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
- p:dataSource-ref="appDS"/>
- <tx:annotation-driven transaction-manager="txMangager" proxy-target-class="true"/>
(2)读写
- @Resource(name = "lobHandler")
- private LobHandler lobHandler;
- @Resource(name = "jdbcTemplate")
- private JdbcTemplate jdbcTemplate;
- public void savePost(final Post post) {
- String sql = " INSERT INTO t_post(post_id,user_id,post_text,post_attach)"
- + " VALUES(?,?,?,?)";
- jdbcTemplate().execute(sql,
- new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) {
- protected void setValues(PreparedStatement ps,
- LobCreator lobCreator) throws SQLException {
- ps.setInt(1, incre.nextIntValue());
- ps.setInt(2, post.getUserId());
- lobCreator.setClobAsString(ps, 3, post.getPostText());
- lobCreator.setBlobAsBytes(ps, 4, post.getPostAttach());
- }
- });
- }
- public List findAttachs(final int userId){
- String sql = "SELECT post_id,post_attach FROM t_post where user_id =? and post_attach is not null";
- return jdbcTemplate().query( sql, new Object[] {userId},
- new RowMapper() {
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- Post post = new Post();
- int postId = rs.getInt(1);
- byte[] attach = lobHandler.getBlobAsBytes(rs, 2);
- post.setPostId(postId);
- post.setPostAttach(attach);
- return post;
- }
- });
- }
一个spring jdbc实例的更多相关文章
- Spring+JDBC实例
1. Customer 表 在这个例子中,我们使用的是MySQL数据库. CREATE TABLE `customer` ( `CUST_ID` int(10) unsigned NOT NULL A ...
- Spring JDBC SqlUpdate类示例
org.springframework.jdbc.object.SqlUpdate类提供了表示SQL更新的可重用操作对象. 使用到的 Student 表的结构如下 - CREATE TABLE Stu ...
- Spring JDBC StoredProcedure类示例
org.springframework.jdbc.core.StoredProcedure类是RDBMS存储过程的对象抽象的超类.这个类是抽象的,目的是让子类将提供一个用于调用的类型化方法,该方法委托 ...
- Spring JDBC SqlQuery类示例
org.springframework.jdbc.object.SqlQuery类提供了表示SQL查询的可重用操作对象. 使用到的 Student 表的结构如下 - CREATE TABLE Stud ...
- Spring JDBC SimpleJdbcCall类示例
org.springframework.jdbc.core.SimpleJdbcCall类是表示对存储过程或存储函数的调用的多线程,可重用的对象. 它提供元数据处理以简化访问基本存储过程/函数所需的代 ...
- Spring JDBC NamedParameterJdbcTemplate类示例
org.springframework.jdbc.core.NamedParameterJdbcTemplate类是一个具有基本JDBC操作的模板类,允许使用命名参数而不是传统的’?‘占位符. 这个类 ...
- Spring JDBC SimpleJdbcInsert类示例
org.springframework.jdbc.core.SimpleJdbcInsert类是一个多线程,可重用的对象,为将数据插入表提供了易用的功能.它提供元数据处理以简化构建基本insert语句 ...
- Spring JDBC RowMapper接口示例
JdbcTemplate类使用org.springframework.jdbc.core.RowMapper <T>接口在每行的基础上映射ResultSet的行.该接口的实现执行将每行映射 ...
- Spring JDBC ResultSetExtractor接口示例
org.springframework.jdbc.core.ResultSetExtractor接口是JdbcTemplate的查询方法使用的回调接口.此接口的实现执行从ResultSet提取结果的实 ...
随机推荐
- ■Ascii逐字解码法注入,mysql5.0一下版本手工注入
/*By:珍惜少年时*/ 逐字解码法,不一定非要猜字段内容.库名,表名,字段,data,都能猜. 环境过滤了select.union(mysql5.0以下的版本就不支持union所以也可以用此方法), ...
- 深度学习入门教程UFLDL学习实验笔记二:使用向量化对MNIST数据集做稀疏自编码
今天来做UFLDL的第二个实验,向量化.我们都知道,在matlab里面基本上如果使用for循环,程序是会慢的一逼的(可以说基本就运行不下去)所以在这呢,我们需要对程序进行向量化的处理,所谓向量化就是将 ...
- sharepoint获取域名和当前登录的应为名字
string a = SPContext.Current.Web.CurrentUser.ToString(); int length = a.IndexOf("w|", 0) ...
- 【转】solr+ajax智能拼音详解---solr跨域请求
本文转自:http://blog.csdn.net/wangzhaodong001/article/details/8529090 最近刚做完solr的ajax智能拼音.总结一下. 前端:jQuery ...
- 使用php递归计算目录大小
统计一个目录大小,因为不知道目录中子目录的深度,所以for循环很难实现,但是用递归调用很容易实现,只要统计出一个目录中所有文件的大小,那么每一次调用就可以了,随便建了个目录,建立一些文件,方法代码如下 ...
- codeforces C. Vasily the Bear and Sequence 解题报告
题目链接:http://codeforces.com/problemset/problem/336/C 题目意思:给出一个递增的正整数序列 a1, a2, ..., an,要求从中选出一堆数b1, b ...
- Codeforces 424C(异或)
Magic Formulas Time Limit: 2000MS Memory Limit: 262144KB 64bit IO Format: %I64d & %I64u Subm ...
- DOS 循环读取txt每一行内容
在命令行窗口中输入: for /f %i in (f:\mydata.txt) do echo %i 如果要是写成批处理文件run.bat for /f %%i in (f:\mydata.txt) ...
- javascript类的类比详解-大白话版
转载请注明出处:水车 如果有误,还望指出,谢谢 -----------------正文分割线---------------------- 类:类太抽象,要想弄明白就该用现实的东西来类比 在我看来类就是 ...
- GPU CUDA 经典入门指南
转自:http://luofl1992.is-programmer.com/posts/38830.html CUDA编程中,习惯称CPU为Host,GPU为Device.编程中最开始接触的东西恐怕是 ...