Java的Spring框架中DAO数据访问对象的使用示例
SpringDAO之JDBC
Spring提供的DAO(数据访问对象)支持主要的目的是便于以标准的方式使用不同的数据访问技术,如JDBC,Hibernate或者JDO等。它不仅可以让你方便地在这些持久化技术间切换,而且让你在编码的时候不用考虑处理各种技术中特定的异常。
为了便于以一种一致的方式使用各种数据访问技术,如JDBC、JDO和Hibernate,Spring提供了一套抽象DAO类供你扩展。这些抽象类提供了一些方法,通过它们你可以获得与你当前使用的数据访问技术相关的数据源和其他配置信息。
Dao支持类:
JdbcDaoSupport-JDBC数据访问对象的基类。需要一个DataSource,同时为子类提供JdbcTemplate。
HibernateDaoSupport-Hibernate数据访问对象的基类。需要一个SessionFactory,同时为子类提供HibernateTemplate。也可以选择直接通过提供一个HibernateTemplate来初始化,这样就可以重用后者的设置,例如SessionFactory,flush模式,异常翻译器(exceptiontranslator)等等。
JdoDaoSupport-JDO数据访问对象的基类。需要设置一个PersistenceManagerFactory,同时为子类提供JdoTemplate。
JpaDaoSupport-JPA数据访问对象的基类。需要一个EntityManagerFactory,同时为子类提供JpaTemplate。
本节主要讨论Sping对JdbcDaoSupport的支持。
下面是个例子:
droptableifexistsuser; /*==============================================================*/ /*Table:user*/ /*==============================================================*/ createtableuser ( idbigintAUTO_INCREMENTnotnull, namevarchar(24), ageint, primarykey(id) );
publicclassUser{ privateIntegerid; privateStringname; privateIntegerage; publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } }
/** *CreatedbyIntelliJIDEA.<br> *<b>User</b>:leizhimin<br> *<b>Date</b>:2008-4-2215:34:36<br> *<b>Note</b>:DAO接口 */ publicinterfaceIUserDAO{ publicvoidinsert(Useruser); publicUserfind(Integerid); } importjavax.sql.DataSource; importjava.sql.Connection; importjava.sql.SQLException; /** *CreatedbyIntelliJIDEA.<br> *<b>Note</b>:基类DAO,提供了数据源注入 */ publicclassBaseDAO{ privateDataSourcedataSource; publicDataSourcegetDataSource(){ returndataSource; } publicvoidsetDataSource(DataSourcedataSource){ this.dataSource=dataSource; } publicConnectiongetConnection(){ Connectionconn=null; try{ conn=dataSource.getConnection(); }catch(SQLExceptione){ e.printStackTrace(); } returnconn; } } /** *CreatedbyIntelliJIDEA.<br> *<b>User</b>:leizhimin<br> *<b>Date</b>:2008-4-2215:36:04<br> *<b>Note</b>:DAO实现 */ publicclassUserDAOextendsBaseDAOimplementsIUserDAO{ publicJdbcTemplategetJdbcTemplate(){ returnnewJdbcTemplate(getDataSource()); } publicvoidinsert(Useruser){ Stringname=user.getName(); intage=user.getAge().intValue(); //jdbcTemplate.update("INSERTINTOuser(name,age)" //+"VALUES('"+name+"',"+age+")"); Stringsql="insertintouser(name,age)values(?,?)"; getJdbcTemplate().update(sql,newObject[]{name,age}); } publicUserfind(Integerid){ Listrows=getJdbcTemplate().queryForList( "SELECT*FROMuserWHEREid="+id.intValue()); Iteratorit=rows.iterator(); if(it.hasNext()){ MapuserMap=(Map)it.next(); Integeri=newInteger(userMap.get("id").toString()); Stringname=userMap.get("name").toString(); Integerage=newInteger(userMap.get("age").toString()); Useruser=newUser(); user.setId(i); user.setName(name); user.setAge(age); returnuser; } returnnull; } }
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEbeansPUBLIC"-//SPRING/DTDBEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <beanid="dataSource" class="org.apache.commons.dbcp.BasicDataSource"singleton="true"> <propertyname="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <propertyname="url"> <value>jdbc:mysql://localhost:3306/springdb</value> </property> <propertyname="username"> <value>root</value> </property> <propertyname="password"> <value>leizhimin</value> </property> </bean> <beanid="baseDAO"class="com.lavasoft.springnote.ch05_jdbc03_temp.BaseDAO"abstract="true"> <propertyname="dataSource"> <refbean="dataSource"/> </property> </bean> <beanid="userDAO" class="com.lavasoft.springnote.ch05_jdbc03_temp.UserDAO"parent="baseDAO"> </bean> </beans>
importorg.springframework.context.ApplicationContext; importorg.springframework.context.support.FileSystemXmlApplicationContext; /** *CreatedbyIntelliJIDEA.<br> *<b>User</b>:leizhimin<br> *<b>Date</b>:2008-4-2215:59:18<br> *<b>Note</b>:测试类,客户端 */ publicclassSpringDAODemo{ publicstaticvoidmain(String[]args){ ApplicationContextcontext=newFileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc03_temp\\bean-jdbc-temp.xml"); Useruser=newUser(); user.setName("hahhahah"); user.setAge(newInteger(22)); IUserDAOuserDAO=(IUserDAO)context.getBean("userDAO"); userDAO.insert(user); user=userDAO.find(newInteger(1)); System.out.println("name:"+user.getName()); } }
运行结果:
log4j:WARNNoappenderscouldbefoundforlogger(org.springframework.core.CollectionFactory). log4j:WARNPleaseinitializethelog4jsystemproperly. name:jdbctemplate Processfinishedwithexitcode0
SpringDAO之Hibernate
HibernateDaoSupport-Hibernate数据访问对象的基类。需要一个SessionFactory,同时为子类提供HibernateTemplate。也可以选择直接通过提供一个HibernateTemplate来初始化,这样就可以重用后者的设置,例如SessionFactory,flush模式,异常翻译器(exceptiontranslator)等等。
本节主要讨论Sping对HibernateTemplate的支持。
下面是个例子:
droptableifexistsuser; /*==============================================================*/ /*Table:user*/ /*==============================================================*/ createtableuser ( idbigintAUTO_INCREMENTnotnull, namevarchar(24), ageint, primarykey(id) );
/** *CreatedbyIntelliJIDEA.<br> *<b>Note</b>:Hiberante实体类 */ publicclassUser{ privateIntegerid; privateStringname; privateIntegerage; publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } }
<?xmlversion="1.0"encoding="utf-8"?> <!DOCTYPEhibernate-mapping PUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <classname="com.lavasoft.springnote.ch06_hbm_02deTx.User" table="user"> <idname="id"column="id"> <generatorclass="native"/> </id> <propertyname="name"column="name"/> <propertyname="age"column="age"/> </class> </hibernate-mapping>
/** *CreatedbyIntelliJIDEA.<br> *<b>User</b>:leizhimin<br> *<b>Date</b>:2008-4-2315:37:43<br> *<b>Note</b>:DAO接口 */ publicinterfaceIUserDAO{ publicvoidinsert(Useruser); publicUserfind(Integerid); } importorg.hibernate.SessionFactory; importorg.springframework.orm.hibernate3.HibernateTemplate; /** *CreatedbyIntelliJIDEA.<br> *<b>User</b>:leizhimin<br> *<b>Date</b>:2008-4-2315:15:55<br> *<b>Note</b>:DAO实现 */ publicclassUserDAOimplementsIUserDAO{ privateHibernateTemplatehibernateTemplate; publicvoidsetSessionFactory(SessionFactorysessionFactory){ this.hibernateTemplate=newHibernateTemplate(sessionFactory); } publicvoidinsert(Useruser){ hibernateTemplate.save(user); System.out.println("所保存的User对象的ID:"+user.getId()); } publicUserfind(Integerid){ Useruser=(User)hibernateTemplate.get(User.class,id); returnuser; } }
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEbeansPUBLIC"-//SPRING/DTDBEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <beanid="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <propertyname="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <propertyname="url"> <value>jdbc:mysql://localhost:3306/springdb</value> </property> <propertyname="username"> <value>root</value> </property> <propertyname="password"> <value>leizhimin</value> </property> </bean> <beanid="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" destroy-method="close"> <propertyname="dataSource"> <refbean="dataSource"/> </property> <propertyname="mappingResources"> <list> <value>com/lavasoft/springnote/ch06_hbm_02proTx/User.hbm.xml</value> </list> </property> <propertyname="hibernateProperties"> <props> <propkey="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> </bean> <beanid="userDAO"class="com.lavasoft.springnote.ch06_hbm_02proTx.UserDAO"> <propertyname="sessionFactory"> <refbean="sessionFactory"/> </property> </bean> </beans>
importorg.springframework.context.ApplicationContext; importorg.springframework.context.support.FileSystemXmlApplicationContext; /** *CreatedbyIntelliJIDEA.<br> *<b>Note</b>:测试类、客户端 */ publicclassSpringHibernateDemo{ publicstaticvoidmain(String[]args){ ApplicationContextcontext=newFileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch06_hbm_02proTx\\bean-hbm_tx.xml"); //建立DAO物件 IUserDAOuserDAO=(IUserDAO)context.getBean("userDAO"); Useruser=newUser(); user.setName("caterpillar"); user.setAge(newInteger(30)); userDAO.insert(user); user=userDAO.find(newInteger(1)); System.out.println("name:"+user.getName()); } }
运行结果:
log4j:WARNNoappenderscouldbefoundforlogger(org.springframework.core.CollectionFactory). log4j:WARNPleaseinitializethelog4jsystemproperly. 所保存的User对象的ID:18 name:jdbctemplate Processfinishedwithexitcode0