package com.h3.customer.model; import java.sql.resultset; import java.sql.sqlexception; import org.springframework.jdbc.core.rowmapper; public class customerrowmapper implements rowmapper { public object maprow(resultset rs, int rownum) throws sqlexception { customer customer = new customer(); customer.setcustid(rs.getint("cust_id")); customer.setname(rs.getstring("name")); customer.setage(rs.getint("age")); return customer; } }
public customer findbycustomerid(int custid){ string sql = "select * from customer where cust_id = ?"; customer customer = getsimplejdbctemplate().queryforobject( sql, new customerparameterizedrowmapper(), custid); return customer; }
public customer findbycustomerid2(int custid){ string sql = "select * from customer where cust_id = ?"; customer customer = getsimplejdbctemplate().queryforobject(sql, parameterizedbeanpropertyrowmapper.newinstance(customer.class), custid); return customer; }
public list<customer> findall(){ string sql = "select * from customer"; list<customer> customers = getsimplejdbctemplate().query(sql, parameterizedbeanpropertyrowmapper.newinstance(customer.class)); return customers; }
public string findcustomernamebyid(int custid){ string sql = "select name from customer where cust_id = ?"; string name = getsimplejdbctemplate().queryforobject( sql, string.class, custid); return name; }
public int findtotalcustomer(){ string sql = "select count(*) from customer"; int total = getsimplejdbctemplate().queryforint(sql); return total; }
运行它
package com.h3.common; import java.util.arraylist; import java.util.list; import org.springframework.context.applicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; import com.h3.customer.dao.customerdao; import com.h3.customer.model.customer; public class simplejdbctemplateapp { public static void main( string[] args ) { applicationcontext context = new classpathxmlapplicationcontext("spring-customer.xml"); customerdao customersimpledao = (customerdao) context.getbean("customersimpledao"); customer customera = customersimpledao.findbycustomerid(1); system.out.println("customer a : " + customera); customer customerb = customersimpledao.findbycustomerid2(1); system.out.println("customer b : " + customerb); list<customer> customeras = customersimpledao.findall(); for(customer cust: customeras){ system.out.println("customer as : " + customeras); } list<customer> customerbs = customersimpledao.findall2(); for(customer cust: customerbs){ system.out.println("customer bs : " + customerbs); } string customername = customersimpledao.findcustomernamebyid(1); system.out.println("customer name : " + customername); int total = customersimpledao.findtotalcustomer(); system.out.println("total : " + total); } }