SpringJdbc的应用举例
这几天在研究底层框架的异同,突然想起还有个springJdbc好像以前用过还不错,可是如何在不使用ssh框架的前提下单独使用spring的jdbc这还是头一次,让我头疼了一下,终于还是搞定了,以下是我整个测试过程的全部应用代码、测试代码、及配置文件详细情况。
第一步:先写好一个实体类People:
package com.ego.springjdbc.vo;import java.io.Serializable;import java.sql.Date;public class People implements Serializable{private int id; private String name; private Date birthDay; private Boolean sex; private Double weight; private float height;public People(){}public People(int id, String name, Date birthDay, Boolean sex,Double weight, float height) {super();this.id = id;this.name = name;this.birthDay = birthDay;this.sex = sex;this.weight = weight;this.height = height;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthDay() {return birthDay;}public void setBirthDay(Date birthDay) {this.birthDay = birthDay;}public Boolean getSex() {return sex;}public void setSex(Boolean sex) {this.sex = sex;}public Double getWeight() {return weight;}public void setWeight(Double weight) {this.weight = weight;}public float getHeight() {return height;}public void setHeight(float height) {this.height = height;}@Overridepublic String toString() {return "People [birthDay=" + birthDay + ", height=" + height + ", id="+ id + ", name=" + name + ", sex=" + sex + ", weight=" + weight+ "]";}}#MySql数据库连接参数配置driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/testibatisusername=rootpassword=111111
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> <!-- <bean id="sessionFactory" ref="dataSource"/> </bean> --> <bean id="peopleDaoImpl" ref="dataSource"/> </bean></beans>package com.ego.springjdbc.dao.impl;import java.io.Serializable;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Map;import org.springframework.jdbc.core.BatchPreparedStatementSetter;import org.springframework.jdbc.core.RowMapper;import org.springframework.jdbc.core.support.JdbcDaoSupport;import com.ego.springjdbc.dao.PeopleDao;import com.ego.springjdbc.vo.People;public class PeopleDaoImpl extends JdbcDaoSupport implements PeopleDao {public int[] batchUpdate(final List<People> pList) {return this.getJdbcTemplate().batchUpdate("update t_people set weight=? where id=?",new BatchPreparedStatementSetter() {public void setValues(PreparedStatement ps, int i) throws SQLException {ps.setDouble(1,pList.get(i).getWeight());ps.setInt(2, pList.get(i).getId());}public int getBatchSize() {return pList.size();}});}/** * 删除记录 */public void doDeleteObj(int id) {System.out.println("id"+id);this.getJdbcTemplate().update("delete from t_people where id=?",new Object[]{id});}/** * 保存对象到数据库 */public void doSaveObj(People p) {this.getJdbcTemplate().update("insert into t_people(name,birthDay,sex,weight,height) values(?,?,?,?,?)",new Object[]{p.getName(),p.getBirthDay(),p.getSex(),p.getWeight(),p.getHeight()},new int[]{java.sql.Types.VARCHAR,java.sql.Types.TIMESTAMP,java.sql.Types.BOOLEAN,java.sql.Types.DOUBLE,java.sql.Types.FLOAT});}/** * 更新数据 */public void doUpdateObj(People p) {this.getJdbcTemplate().update("update t_people set weight=?,height=? where id=?",new Object[]{p.getWeight(),p.getHeight(),p.getId()});}/** * 获取记录总数 */public int getCountEntites() {return this.getJdbcTemplate().queryForInt("select count(*) from t_people");}/** * 获取数据集合 */@SuppressWarnings("unchecked")public List<Map<String, Object>> getList() {return this.getJdbcTemplate().queryForList("select * from t_people");}/** * 获取单个对象 */public Serializable getObjByID(int id) {String sql = "select * from t_people where id=?";People people = (People)this.getJdbcTemplate().queryForObject(sql,new Object[]{id},new RowMapper(){public People mapRow(ResultSet rst, int arg1) throws SQLException {People p = new People();p.setId(rst.getInt("id")); p.setName(rst.getString("name")); p.setBirthDay(rst.getDate("birthDay")); p.setWeight(rst.getDouble("weight")); p.setHeight(rst.getFloat("height")); p.setSex(rst.getBoolean("sex")); return p;}});return people;}/** * 通过ID获取符合条件的对象集合 */@SuppressWarnings("unchecked")public List<People> getObjsByID(int id) {List<People> pList = this.getJdbcTemplate().query("select * from t_people where id > ?",new Object[]{id}, new RowMapper() {public People mapRow(ResultSet rst, int rownum) throws SQLException {People p = new People();p.setId(rst.getInt("id")); p.setName(rst.getString("name")); p.setBirthDay(rst.getDate("birthDay")); p.setWeight(rst.getDouble("weight")); p.setHeight(rst.getFloat("height")); p.setSex(rst.getBoolean("sex")); return p;}});return pList;}/** * MySql分页查询 */@SuppressWarnings("unchecked")public List<People> getPeopleList(int pageSize, int currentPage) {String sql ="select * from t_people limit ?,?";List<People> pList = this.getJdbcTemplate().query(sql,new Object[]{(currentPage-1)*pageSize,pageSize},new RowMapper() {public People mapRow(ResultSet rst, int arg1) throws SQLException {People p = new People();p.setId(rst.getInt("id")); p.setName(rst.getString("name")); p.setBirthDay(rst.getDate("birthDay")); p.setWeight(rst.getDouble("weight")); p.setHeight(rst.getFloat("height")); p.setSex(rst.getBoolean("sex")); return p;}});return pList;}}package com.ego.springjdbc.test;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import sun.net.www.content.text.plain;import com.ego.springjdbc.dao.PeopleDao;import com.ego.springjdbc.vo.People;public class PeopleTest {public static void main(String[] args) {PeopleDao peopleDao = null;//加载spring的配置文件ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");//获取实现类实例,注意这里不能用PeopleDao peopleDao = new PeopleDaoImpl();peopleDao=(PeopleDao)ac.getBean("peopleDaoImpl");//测试添加操作//People people = new People();//people.setName("Yao");//java.util.Date date = new java.util.Date();//Long time = date.getTime();//people.setBirthDay(new java.sql.Date(time));//people.setSex(true);//people.setWeight(58.0);//Float height = new Float(158.0);//people.setHeight(height);//peopleDao.doSaveObj(people);//System.out.println("保存成功!");//测试删除操作//peopleDao.doDeleteObj(5);//System.out.println("删除成功!");//测试更新操作//People people = new People();//people.setId(16);//people.setWeight(80.0);//Float height = new Float(180.0);//people.setHeight(height);//peopleDao.doUpdateObj(people);//System.out.println("更新成功!");//测试获取记录总数//int n = peopleDao.getCountEntites();//System.out.println("记录总数:"+n);//获取数据集合//通过ID查询单个对象//People p = (People)peopleDao.getObjByID(8);//System.out.println("people:"+p.toString());//通过ID查询对象集合//List<People> pList = new ArrayList<People>();//pList = peopleDao.getObjsByID(7);//for(People p:pList){//System.out.println("people:"+p.toString());//}//MySql分页查询//List<People> pList = peopleDao.getPeopleList(3, 3);//for(People p:pList){//System.out.println("people:"+p.toString());//}//测试获取List<Map<String,Object>>List<Map<String, Object>> pList = peopleDao.getList();//遍历map的几种方法://方法一:System.out.println("方法一:");for(Map map:pList){printMapMethodOne(map);}//方法二:System.out.println("方法二:");for(Map map:pList){printMapMethodTwo(map);}//方法三:System.out.println("方法三:");for(Map map:pList){printMapMethodThree(map);}//批量修改System.out.println("批量修改");List<People> pList2 = new ArrayList<People>();int id=7;for(int i=0;i<6;i++){System.out.println("id"+id);People people=new People();people.setId(id);people.setWeight(30.0+i);pList2.add(people);id++;}System.out.println("批处理数据:"+peopleDao.batchUpdate(pList2));}/** * 遍历map方法一: * @param map */public static void printMapMethodOne(Map map){Collection<Object> collection = map.values();Collection<Object> collection2 = map.keySet();Iterator it = collection.iterator();Iterator it2 = collection2.iterator();while(it.hasNext()&&it2.hasNext()){System.out.println(it2.next()+" --> "+it.next()+" ");}}/** * 遍历map方法二: * @param map */public static void printMapMethodTwo(Map map){Set<String> key = map.keySet();Iterator it = key.iterator();while(it.hasNext()){String s = (String)it.next();System.out.println(s+" --> "+map.get(s));}}/** * 遍历map方法三: * @param map */public static void printMapMethodThree(Map map){Set<Map.Entry<String,Object>> set = map.entrySet();Iterator<Map.Entry<String, Object>> it = set.iterator();while(it.hasNext()){Map.Entry<String,Object> entry =it.next();System.out.println(entry.getKey()+" --> "+entry.getValue());}}}<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring.xml</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>