J2EE學(xué)習(xí)筆記
          我們的失落……
          posts - 13,comments - 1,trackbacks - 0
          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方法中被創(chuàng)建-->   
              
          <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>      
              
          <!-- 配置事務(wù)屬性 -->   
             
          <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 {   
              
          /**  
               * 根據(jù)SQL建表  
               * 
          @param sql  
               
          */
            
              
          public void createTableBySQL(String sql);   
            
              
          /**  
               * 統(tǒng)計firstName相同的總數(shù)  
               * 
          @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);   
                 
              
          /**  
               * 插入/更新/刪除數(shù)據(jù)  
               * 
          @param sql 有參數(shù)語句  
               * 
          @param obj 參數(shù)值數(shù)組  
               
          */
            
              
          public int operateActor(String sql,Object[] obj);   
            
              
          /**  
               * 根據(jù)SQL查詢記錄總數(shù)  
               * 
          @param sql  
               * 
          @return  
               
          */
            
              
          public int findRowCountBySQL(String sql);   
            
              
          /**  
               * 根據(jù)Id查找指定對象  
               * 
          @param id  
               * 
          @return  
               
          */
            
              
          public Actor findActorById(long id);   
            
              
          /**  
               * 根據(jù)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.接口實現(xiàn)
          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封裝,增加了命名參數(shù)特性   
              private NamedParameterJdbcTemplate namedParameterJdbcTemplate;   
            
              
          //SimpleJdbcTemplate對JdbcTemplate封裝,某些特性要在java5以上才工作   
              private SimpleJdbcTemplate simpleJdbcTemplate;   
                 
              
          //簡化插入數(shù)據(jù)操作   
              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();   
              }
             
                 
              
          /**  
               * 統(tǒng)計firstName相同的總數(shù)  
               * 
          @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);   
              }
             
            
              
          /**  
               * 根據(jù)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;   
              }
             
                 
              
          /**  
               * 插入/更新/刪除數(shù)據(jù)  
               * 
          @param sql 有參數(shù)語句  
               * 
          @param obj 參數(shù)值數(shù)組  
               
          */
            
              
          public int operateActor(String sql,Object[] obj){   
                  
          return this.jdbcTemplate.update(sql, obj);   
              }
             
            
              
          /**  
               * 根據(jù)SQL查詢記錄總數(shù)  
               * 
          @param sql  
               * 
          @return  
               
          */
            
              
          public int findRowCountBySQL(String sql){   
                  
          return this.jdbcTemplate.queryForInt(sql);   
              }
             
                 
              
          /**  
               * 根據(jù)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;   
              }
             
            
            
              
          /**  
               * 根據(jù)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());   
              }
             
                 
              
          /**  
               * 定義一個靜態(tài)內(nèi)部類,在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){   
                  
          //如果對象數(shù)組與占位符出現(xiàn)位置一一對應(yīng)   
                  
          //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));   
                  
          //根據(jù)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());   
                  }
             
              }
             
          }
          posted on 2010-03-09 19:10 J2EE學(xué)習(xí)筆記 閱讀(2017) 評論(0)  編輯  收藏 所屬分類: 轉(zhuǎn)載 、spring
          主站蜘蛛池模板: 安西县| 商河县| 竹山县| 高要市| 大兴区| 井陉县| 邢台市| 六安市| 五常市| 额济纳旗| 台湾省| 攀枝花市| 疏勒县| 桂平市| 紫金县| 灌南县| 敖汉旗| 阳西县| 镶黄旗| 拉萨市| 宜昌市| 同德县| 金门县| 德江县| 灵石县| 顺昌县| 庆城县| 军事| 南平市| 赤水市| 赫章县| 始兴县| 谢通门县| 惠水县| 柯坪县| 旬阳县| 华蓥市| 洛宁县| 日照市| 静安区| 长春市|