Eclipse uses Spring JDBC Template to write DAO

xiaoxiao2021-03-06  70

DAO should be a popular development model now. Whether it is using what update technology, hibernate or other .dao mode should follow. I write DAO probably this: a DAO interface, define how to implement Name; an IMPL implementation class, mainly controls the connection and shutting down the database; there will be a database implementation class that write specific methods; there is a factory class, which can be more flexible to achieve different DAOs. The above means feel good, but It is more troublesome to write, and if you use the database connection pool, you will be more troublesome when using JUnit to test. Let's write a DAO test instance using Spring, you will find it simple and practical. Used DBCP connection pool.

The following is the JAR package to be introduced

Springdao.java file

Package com.bcxy.spring.da;

Import java.sql.preparedStatement; import java.sql.resultset; import java.sql.sqlexception; import java.util.arrayList; import java.util.list;

Import javax.sql.datasource;

import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc .core.rowcallbackhandler; import com.bcxy.spring.dao.model.testmodel;

Public class springdao {

DataSource ds = null; JdbcTemplate jt = null; Log log = LogFactory.getLog (SpringDao.class); public List springQuery () {final List tests = new ArrayList (); String sql = "select * from test"; jt = new JDBCTemplate (DS); JT.Query (SQL, New RowCallbackHandler () {

Public void processrow (ResultSet RS) throws Sqlexception {// TestModel TM = New TestModel (); Tm.SetId (Rs.Getint ("ID")); TM.STPW (rs.getstring ("pw")); TM. Setun ("UN"))); // Tests.Add (TM);}}); returnids;} public void SpringUpdate () {string sql = "Update test set pw =? where id =?" JT = New JDBCTemplate (DS); JT.Update (SQL, New PreparedStatementSetter () {Public Void SetValues ​​(PREPAREDSTATEMENT PS) throws sqlexception {// ps.setstring (1, "maxcard"); ps.setint (2, 1 );}}); Log.info ("Update Test A Record.");

/ ** * @Return * / public datasource getds () {return DS;}

/ ** * @Param Source * / public void setds (Datasource Source) {ds = source;

}

Spring profile

Spring Quick Start com.mysql.jdbc.driver jdbc: mysql: // localhost / test

Below we use JUnit test: ......

public void testSpringUpdate () throws FileNotFoundException {// InputStream is = new FileInputStream ( "bean.xml"); XmlBeanFactory bean = new XmlBeanFactory (is); SpringDao sd = (SpringDao) bean.getBean ( "testdao"); sd.springUpdate ();

... After the success is successful, check the database ....

What is wrong with you? Webmaster@bcxy.com

转载请注明原文地址:https://www.9cbs.com/read-108409.html

New Post(0)