SpringJdbc的应用举例

本文详细介绍了如何在不使用SSH框架的前提下,单独使用Spring的JDBC进行数据库操作,包括实体类设计、配置Spring环境、创建DAO接口及其实现类、以及进行数据库增删改查操作的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   这几天在研究底层框架的异同,突然想起还有个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;
	}


	@Override
	public String toString() {
		return "People [birthDay=" + birthDay + ", height=" + height + ", id="
				+ id + ", name=" + name + ", sex=" + sex + ", weight=" + weight
				+ "]";
	}
}


第二步就是配置一个只有spring的环境:
添加spring的jar包和数据库的驱动包这个就不说了。主要是配置spring.xml和读取数据库连接参数database.properties属性文件。


database.properties属性文件:

#MySql数据库连接参数配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/testibatis
username=root
password=111111


spring.xml配置文件:

<?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.xsd
		http://www.springframework.org/schema/aop
		http://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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	        <property name="locations">
	            <value>classpath:database.properties</value>
	        </property>
	    </bean>
  		<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  			<property name="driverClassName" value="${driver}"/>
  			<property name="url" value="${url}"/>
  			<property name="username" value="${username}"/>
  			<property name="password" value="${password}"/>
  		</bean>
     	<!-- 
     	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     		<property name="dataSource" ref="dataSource"/>
     	</bean>
     	-->
     	<bean id="peopleDaoImpl" class="com.ego.springjdbc.dao.impl.PeopleDaoImpl">
     		<property name="dataSource" ref="dataSource"/>
     	</bean>
</beans>



第三步(最要的一步):写底层的Dao,我这里是引用了接口的,我直接将实现类代码贴上,接口的就不贴了,相信大家都懂得,实现类里面的方法和接口是一样的。

实现类PeopleDaoImpl.java:


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

}



第四步:这步就简单了,注意获取底层实现类的方法就行了,必须要先加载spring的配置文件。

测试类PeopleTest.java:


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());
		}
	}
	
	
	
}




最后还有一点需要注意:我这里建立的项目是WebProject所以还需要配置一个web.xml文件:


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


本篇主体思想是参考文章 http://zhengchao123.iteye.com/blog/1017538请大家尊重原创。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值