Spring的DAO模块提供了对JDBC、Hibernate、JDO等DAO层支持。

DAO模块依赖 commons-pool.jar、commons-collections.jar

package com.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class IPeopleDaoImpl extends JdbcDaoSupport implements IPeopleDao{ public void initDatabase(){//创建表
String sql="create table People(" +
"id int primary key auto_increment," +
"name varchar(100) not null," +
"age int,"+
"sex varchar(10)," +
"birthday DateTime)";
getJdbcTemplate().execute(sql);
} public void addPeople(People people) {
String sql="insert into people(name,sex,age,birthday)" +
"values(?,?,?,?)";
getJdbcTemplate().update(
sql,new Object[]{
people.getName(),people.getSex(),people.getAge(),people.getBirthday()
});
} public int getPeopleCount() {
String sql="select count(*) from people";
int count=getJdbcTemplate().queryForInt(sql);
return count;
} public String getPeopleName(int id) {
String sql="select name from people where id="+id;
String name=getJdbcTemplate().queryForObject(sql, String.class);
return name;
} public List<People> listPeoples() {
String sql="select * from people";
List<Map<String,Object>> list=getJdbcTemplate().queryForList(sql);
List<People> peopleList=new ArrayList<People>(); for(Map<String,Object> row: list){
People people=new People();
people.setId((Integer)row.get("id"));
people.setName((String)row.get("name"));
people.setSex((String)row.get("sex"));
people.setBirthday((Date)row.get("birthday"));
people.setAge((Integer)row.get("age"));
peopleList.add(people);
}
return peopleList;
} } <?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!--<bean id="aopMethodBeforeInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.aop.MethodBeforeInterceptor"></bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean> --><!--<bean id="aopMethodAfterInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.aop.MethodAfterInterceptor">
</bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean>
--> <!--<bean id="aopMethodAfterInterceptor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<bean class="com.aop.MethodAfterInterceptor">
</bean>
</property>
<property name="patterns">
<list>
<value>.*withAop</value>
<value>.*like.*</value>
</list>
</property>
</bean> <bean id="aopThrowsInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.aop.ThrowsInterceptor"></bean>
</property>
<property name="mappedName" value="withAop"></property>
</bean> --><!-- Service对象,安装到ProxyFactoryBean对象中 -->
<!--<bean id="aopService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopMethodBeforeInterceptor</value>
<value>aopMethodAfterInterceptor</value>
<value>aopThrowsInterceptor</value>
</list>
</property>
<property name="target">
<bean class="com.aop.AopServiceImpl">
<property name="name" value="sss"></property>
</bean>
</property>
</bean>
-->
<bean id="configproperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="jdbc.properties"/>
</bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="configproperties"/>
</bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
</bean>
<!--<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="url" value="jdbc:mysql://localhost:3306/test_1?characterEncoding=UTF-8" />
<property name="username" value="guodaxia" />
<property name="password" value="guodaxia" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean> --><bean id="peopleDao" class="com.dao.IPeopleDaoImpl" depends-on="dataSource" >
<property name="dataSource" ref="dataSource" />
</bean> </beans> package com.dao; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class IPeopleDaoImpl extends JdbcDaoSupport implements IPeopleDao{ public void initDatabase(){//创建表
String sql="create table People(" +
"id int primary key auto_increment," +
"name varchar(100) not null," +
"age int,"+
"sex varchar(10)," +
"birthday DateTime)";
getJdbcTemplate().execute(sql);
} public void addPeople(People people) {
String sql="insert into people(name,sex,age,birthday)" +
"values(?,?,?,?)";
getJdbcTemplate().update(
sql,new Object[]{
people.getName(),people.getSex(),people.getAge(),people.getBirthday()
});
} public int getPeopleCount() {
String sql="select count(*) from people";
int count=getJdbcTemplate().queryForInt(sql);
return count;
} public String getPeopleName(int id) {
String sql="select name from people where id="+id;
String name=getJdbcTemplate().queryForObject(sql, String.class);
return name;
} public List<People> listPeoples() {
String sql="select * from people";
List<Map<String,Object>> list=getJdbcTemplate().queryForList(sql);
List<People> peopleList=new ArrayList<People>(); for(Map<String,Object> row: list){
People people=new People();
people.setId((Integer)row.get("id"));
people.setName((String)row.get("name"));
people.setSex((String)row.get("sex"));
people.setBirthday((Date)row.get("birthday"));
people.setAge((Integer)row.get("age"));
peopleList.add(people);
}
return peopleList;
} } package com.dao; import java.util.List; public interface IPeopleDao {
public String getPeopleName(int id);
public void addPeople(People people);
public int getPeopleCount();
public List<People> listPeoples(); } package com.Test; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dao.IPeopleDao;
import com.dao.People; public class TestDao { /*public static void main(String[] args){
String time="2011-12-07";
System.out.println(TransactToDate(time).toLocaleString());
}*/ public static void main(String[] args){
Test1();
} public static void Test1(){
ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
IPeopleDao personDao=(IPeopleDao) con.getBean("peopleDao"); /*People p=new People();
p.setName("Helloween");
p.setSex("男");
p.setAge(12);
p.setBirthday(TransactToDate("2005-12-3"));
personDao.addPeople(p);*/
System.out.println(personDao.getPeopleCount());
List<People> peo=personDao.listPeoples();
System.out.println(peo.get(0).getName());
} public static Date TransactToDate(String d) {
String pattern = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date date=null;
try {
date = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
} }

解析例子:

DaoImpl继承JdbcDaoSupport类

JdbcDaoSupport中有一个dataSource变量,在配置文件中配置数据源的值,使用getJdbcTemplate()获取JdbcTemplate对象,使用JdbcTemplate对象操作数据库

我这里用到的几个方法:

getJdbcTemplate().execute(sql);//我这里用来建表

getJdbcTemplate().update(
                sql,new Object[]{
                        people.getName(),people.getSex(),people.getAge(),people.getBirthday()
                        });//执行update操作,并在sql语句中使用了?通配符使用数组赋值

getJdbcTemplate().queryForInt(sql);//查询操作返回int值

getJdbcTemplate().queryForObject(sql, String.class);//将查询的结果转化成对象

getJdbcTemplate().queryForList(sql);//将查询的结构转化成结果集的List集合

Template()对象具有一些局限性,所以我们可以使用其他类进行操作

MappingSQLQquery抽象类查询

package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException; import org.springframework.jdbc.object.MappingSqlQuery; public class PeopleMappingQuery extends MappingSqlQuery{ @Override
protected Object mapRow(ResultSet rs, int columnIndex) throws SQLException {
People people=new People();
people.setId(rs.getInt("id"));
people.setName(rs.getString("name"));
people.setBirthday(rs.getDate("birthday"));
people.setAge(rs.getInt("age"));
people.setSex(rs.getString("sex"));
return people;
} }
@SuppressWarnings("unchecked")
public List<People> findPeople(int age,String name){
PeopleMappingQuery peopleQuery=new PeopleMappingQuery();
peopleQuery.setDataSource(getDataSource());//因为我是在JdbcDao的继承类中操作的,所以使用getDataSource获取dateSource,当然我在配置文件中将参数设置进去了
peopleQuery.setSql("select * from people where age=? and name=?");
peopleQuery.declareParameter(new SqlParameter(Types.INTEGER));
peopleQuery.declareParameter(new SqlParameter(Types.VARCHAR));
peopleQuery.compile();//遍历结果集 return peopleQuery.execute(new Object[]{age,name});
}
@SuppressWarnings("unchecked")
public List<People> findAllPeople(){
PeopleMappingQuery peopleQuery=new PeopleMappingQuery();
peopleQuery.setDataSource(getDataSource());
peopleQuery.setSql("select * from people");
peopleQuery.compile();//遍历结果集 return peopleQuery.execute(new Object[]{});
}
package com.dao;

import java.util.List;

public interface IPeopleDao {
public String getPeopleName(int id);
public void addPeople(People people);
public int getPeopleCount();
public List<People> listPeoples();
public List<People> findAllPeople();
public List<People> findPeople(int age,String name); }
package com.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dao.IPeopleDao;
import com.dao.People; public class TestDao { /*public static void main(String[] args){
String time="2011-12-07";
System.out.println(TransactToDate(time).toLocaleString());
}*/ public static void main(String[] args){
Test1();
} public static void Test1(){
ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
IPeopleDao personDao=(IPeopleDao) con.getBean("peopleDao"); /*People p=new People();
p.setName("allo");
p.setSex("男");
p.setAge(3);
p.setBirthday(TransactToDate("2013-4-3"));
personDao.addPeople(p);*/
// System.out.println(personDao.getPeopleCount());
// List<People> peo=personDao.listPeoples();
// List<People>peo=personDao.findAllPeople();
List<People>peo=personDao.findPeople(3,"allo");
for(int i=0;i<peo.size();i++){
System.out.println(peo.get(i).getId()+" "+peo.get(i).getName()+" "+peo.get(i).getSex()+" "+peo.get(i).getAge()+" "+peo.get(i).getBirthday().toLocaleString());
}
} public static Date TransactToDate(String d) {
String pattern = "yyyy-MM-dd";
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date date=null;
try {
date = df.parse(d);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
} }

SQLUpdate更新

package com.dao;

import java.sql.Types;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate; public class PeopleUpdate extends SqlUpdate{
public int UpdatePeople(BasicDataSource ds,String name,int id){
setDataSource(ds);
setSql("update people set name=? where id=?"); declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.INTEGER));
compile();//编译sql
return update(new Object[]{name,id});
}
public int addPeople(BasicDataSource ds,People p){
setDataSource(ds); setSql("insert into People(name,sex,age,birthday) values(?,?,?,?)"); declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.DATE));
compile();//编译sql
return update(new Object[]{p.getName(),p.getSex(),p.getAge(),p.getBirthday()});
}
}
public void addPeopleSQLUpadate(People p){
PeopleUpdate up=new PeopleUpdate();
up.addPeople((BasicDataSource) getDataSource(), p);
} public void update(String name,int id){
PeopleUpdate up=new PeopleUpdate();
up.UpdatePeople((BasicDataSource) getDataSource(), name, id);
}
public static void Test1(){
ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
IPeopleDao personDao=(IPeopleDao) con.getBean("peopleDao"); /*People p=new People();
p.setName("guofei");
p.setSex("女");
p.setAge(18);
p.setBirthday(TransactToDate("1998-04-03"));
personDao.addPeopleSQLUpadate(p);*/
personDao.update("wuzhi",1);
}

SQLFunction返回单一结果

默认返回int类型,也可以重载返回其他类型。相当于JdbcTemplate的queryForInt等

Spring的DAO模块的更多相关文章

  1. Spring【DAO模块】就是这么简单

    前言 上一篇Spring博文主要讲解了如何使用Spring来实现AOP编程,本博文主要讲解Spring的DAO模块对JDBC的支持,以及Spring对事务的控制... 对于JDBC而言,我们肯定不会陌 ...

  2. Spring之DAO模块

    Spring的DAO模块提供了对JDBC.Hibernate.JDO等DAO层支持 DAO模块依赖于commons-pool.jar.commons-collections.jar Spring完全抛 ...

  3. Spring DAO模块

    Spring的DAO模块提供了对JDBC.Hibernate.Mybatis等DAO层支持,本节介绍DAO模块对JDBC的支持.DAO模块依赖ommons-dbcp.jar.commons-pool. ...

  4. spring的核心模块有哪些?

    Spring的七个核心模块,供大家参考,具体内容如下 1.Spring core:核心容器 核心容器提供spring框架的基本功能.Spring以bean的方式组织和管理Java应用中的各个组件及其关 ...

  5. Spring第七篇【Spring的JDBC模块】

    前言 上一篇Spring博文主要讲解了如何使用Spring来实现AOP编程,本博文主要讲解Spring的对JDBC的支持- 对于JDBC而言,我们肯定不会陌生,我们在初学的时候肯定写过非常非常多的JD ...

  6. Spring【AOP模块】就是这么简单

    前言 到目前为止,已经简单学习了Spring的Core模块.....于是我们就开启了Spring的AOP模块了...在讲解AOP模块之前,首先我们来讲解一下cglib代理.以及怎么手动实现AOP编程 ...

  7. Maven 搭建spring boot多模块项目(附源码),亲测可以,感谢原创

    原创地址:https://segmentfault.com/a/1190000005020589 我的DEMO码云地址,持续添加新功能: https://gitee.com/itbase/Spring ...

  8. 1.Spring——七大主要模块

    Spring有七大功能模块,分别是Spring Core,AOP,ORM,DAO,MVC,WEB,Content. 下面分别简单介绍: 1.Spring Core Core模块是Spring的核心类库 ...

  9. 一头扎进Spring之---------Spring七大核心模块

    Spring七大核心模块 核心容器(Spring Core) 核心容器提供Spring框架的基本功能.Spring以bean的方式组织和管理Java应用中的各个组件及其关系.Spring使用BeanF ...

随机推荐

  1. [bzoj 1774][Usaco2009 Dec]Toll 过路费

    题目描述 跟所有人一样,农夫约翰以着宁教我负天下牛,休叫天下牛负我的伟大精神,日日夜夜苦思生 财之道.为了发财,他设置了一系列的规章制度,使得任何一只奶牛在农场中的道路行走,都 要向农夫约翰上交过路费 ...

  2. vs2010中自动给函数或者类加上注释宏模板

    Sub AddFunComment() Dim DocSel As EnvDTE.TextSelection DocSel = DTE.ActiveDocument.Selection DocSel. ...

  3. 【Coursera】Sixth Week(2)

    DNS:Domain Name System The Domain Name System convert user-friendly names,like www.umich.edu, to net ...

  4. POJ 1222 EXTENDED LIGHTS OUT(高斯消元解XOR方程组)

    http://poj.org/problem?id=1222 题意:现在有5*6的开关,1表示亮,0表示灭,按下一个开关后,它上下左右的灯泡会改变亮灭状态,要怎么按使得灯泡全部处于灭状态,输出方案,1 ...

  5. Java I/O学习——File

    File我们出看可能会根据字面意思理解为文件,其实它既代表文件又代表目录. 这里有一个例子可以列出指定目录下的所有文件或目录, 以及我们可以过滤得到我们想要的文件 import java.io.Fil ...

  6. MongoDB(课时18 修改器)

    3.4.3.2 修改器(原子操作) 对MongoDB数据库而言,数据的修改会牵扯到内容的变更,结构的变更(包含数组),所以在MongoDB在设计的时候就提供有一系列的修改器的应用,那么像之前使用的“$ ...

  7. JavaScript权威指南--脚本化文档

    知识要点 脚本化web页面内容是javascript的核心目标. 第13章和14章解释了每一个web浏览器窗口.标签也和框架由一个window对象所示.每个window对象有一个document对象, ...

  8. OpenGL入门程序二:绘制简单的圆

    学习 绘制一个圆: ; const float Pi = 3.1415926536f; const float R = 0.5f; //绘制一个圆 void DrawCircle() { //绘制一个 ...

  9. English trip -- VC(情景课)10 B Around the house 在家里

    Vocablulary focus  核心词汇 cook play the guitar listen to music watch TV read magazines work in the gar ...

  10. 3-30 flash(api),rescue_from(); logger简介

    ActionDispatch::Flash < Objec pass temporary primitive-types (String, Array, Hash) between action ...