Spring's DAO module

Source: Internet
Author: User

Spring's DAO module provides support for DAO layers such as JDBC, Hibernate, JDO, etc.

The DAO module relies on Commons-pool.jar, Commons-collections.jar

Spring completely discards the JDBC API, and developers only need to execute the SQL statement using the encapsulated JdbcTemplate, and then get the desired results

DAO Layer Business logic

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 () {//Initialize database} public String Getpersonname (Inte             Ger 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; }     }


Configure the data source

<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>

Return entity Object

Mappingsqlquery is an abstract class that the developer needs to implement its Maprow (Resultset,int) method to implement a mapping from ResultSet to Java objects, which can return the entity class object directly

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 class

Using Sqlupdate to achieve modularity of a function

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)             };< C12/>return update (SQL);}      }

Transaction management

<!--JDBC Transaction management--><bean id= "Jdbctransactionmanager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/></bean> <!--Configure transactions for all methods--><bean id=" Transactionattributesource "class=" Org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource "> <property name=" Properties "> <props> <prop key=" * ">PROPAGATION_REQUIRED</prop><!-- Service Type-</props> </property></bean> <bean id= "Transactiionrun" class= "ORG.SPRINGFR Amework.transaction.interceptor.TransactionProxyFactoryBean "> <property name=" TransactionManager "ref=" Jdbctransactionmanager "/> <property name=" target "> <bean class=" Com.clf.spring.TransactionR      Un "> <property name=" Persondao "ref=" Persondao "></property> </bean> </property> <property name= "Transactionattributesource" ref= "Transactionattributesource"/></bean> 


Transactionrun for user-defined class Transactionrun Transactionrun = Factory.getbean ("Transactionrun"); Transactionrun.run ();


Spring's DAO module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.