Spring之DAO模組,springdao

來源:互聯網
上載者:User

Spring之DAO模組,springdao

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();


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.