Spring之DAO模块

Spring的DAO模块提供了对JDBC、Hibernate、JDO等DAO层支持

DAO模块依赖于commons-pool.jar、commons-collections.jar

Spring完全抛弃了JDBC API,开发者只需要使用封装好的JdbcTemplate执行SQL语句,然后得到需要的结果

DAO层业务逻辑

public interface IpersonDao{
      public String getPersonName(Integer id);
      public void addPerson(Person person);
      public int getPersonCount();
      public List<Person> listPersons();
}
 
import  org.springframework.jdbc.core.support.JdbcDaoSupport;
public classPersonDaoImpl extends JdbcDaoSupport implements IPersonDao{
 
      public void initDatabase(){
             //初始化数据库
      }
      public String getPersonName(Integer id){
             String sql = "select namefrom t_person where id = "+id;
             return (String)getJdbcTemplate().queryForObject(sql,String.class);
      }
      public void addPerson(Person person){
             String sql = "insert intot_person (name,sex,age,birthday) values(?,?,?,?) ";
             Object [] params ={person.getName(),person.getSex(),person.getAge(),person.getBirthday() };
             getJdbcTemplate().update(sql, params);
      }
      public int getPersonCount(){
             String sql = "selectcount(*) from t_person";
             returngetJdbcTemplate().queryForInt(sql);
      }
      public List<Person> listPersons(){
             String sql = "selectid,name,sex,age,birthday from t_person ";
             List<Map<String,Object>>list= getJdbcTemplate().queryForList(sql);
             List<Person> personList  = new ArrayList<Person> ();
             for(Map< String,Object > row: list){
                    Person person = newPerson();
 
                    person.setId((Integer)row.get("id"));
                    person.setName((String)row.get("sex"));
                    person.setSex((String)row.get("name"));
                    person.setAge((Integer)row.get("age"));
                    person.setBirthday((Date)row.get("birthday"));
                    personList.add(person);
             }
             return personList;
      }
     
}


 

配置数据源

<bean id="dataSource" class="org.apche.commons.dbcp.BasicDataSurce" destroy-method="close">
      <property name="diverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/>  
      <property name="username" value="root"/>  
      <property name="password" value="admin"/>  
</bean>
 
<bean id="personDao" class="com.clf.spring.PersonDaoImpl" depends-on=" dataSource"init-method="initDatabase">
      <property name="dataSource" ref="dataSource" />
</bean>
 

返回实体对象

MappingSqlQuery是一个抽象类,开发者需要实现它的mapRow(ResultSet,int)方法实现从ResultSet到Java对象的映射,该方法可以直接返回实体类对象

import  org.springframework.jdbc.object.MappingSqlQuery;
 
public class PersonMappingQuery extends MappingSqlQuery{
      protected Object mapRow(ResultSet rs,int columnIndex) throws SQLException {
             Person person = new Person();
 
             person.setId(rs.getInt("id"));
             person.setName(rs.getString("name"));
             person.setSex(rs.getString("sex"));
             person.setAge(rs.getInt("age"));
             person.setBirthday(rs.getTimstamp("birthday"));
 
             return person;
      }
}
 
public List findAllPersons(){
      PersonMappingQuery personQuery = newPersonMappingQuery();
      personQuery.setDataSource(getDataSource());
      personQuery.setSql("select *from t_person where age > ?");
      personQuery.declareParameter(newSqlParameter(java.sql.Types.NUMERIC));
      personQuery.compile();
      return personQuery.execute(new Object [] {newInteger(25) });
}
 

SqlUpdate类

利用SqlUpdate来实现某个功能的模块化

public class UpdateSql extends SqlUpdate{
      public UpdateSql(DataSource ds){
             setDataSource(ds);
             setSql("……");
             declareParameter(newSqlParameter(Tpyes.NUMERIC));
             declareParameter(newSqlParameter(Tpyes.NUMERIC));
             compile();
      }
     
      public int run(int id,int num){
             Object [] params = new Object [] {
                    new Integer(id),
                    new Integer(num)
             };
             return update(sql);
      }
}

事务管理

<!--  JDBC事务管理-->
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource" />
</bean>
 
<!--  为所有的方法配置事务-->
<bean id="transactionAttributeSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
      <property name="properties">
             <props>
                    <prop key="*">PROPAGATION_REQUIRED</prop><!--事务类型-->
             </props>
      </property>
</bean>
 
<bean id="transactiionRun" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
      <property name="transactionManager" ref=" jdbcTransactionManager" />
      <property name="target" >
             <bean class="com.clf.spring.TransactionRun">
                    <property name="personDao" ref="personDao"></property>
             </bean>
      </property>
      <property name="transactionAttributeSource" ref=" transactionAttributeSource" />
</bean>


// TransactionRun为用户自定义类
TransactionRun transactionRun = factory.getBean("transactionRun");
transactionRun.run();


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。