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. UVa 1220 Hali-Bula的晚会(树的最大独立集)

    https://vjudge.net/problem/UVA-1220 题意: 公司里有n个人形成一个树状结构,即除了老板以外每个员工都有唯一的直属上司.要求选尽量多的人,但不能同时选择一个人和他的直 ...

  2. 使用JavaScript / JQuery导出 html table 数据至 Excel 兼容IE/Chrome/Firefox

    function fnExcelReport() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6'> ...

  3. hdu 2795 Billboard 线段树+二分

    Billboard Time Limit: 20000/8000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Probl ...

  4. ssh 连接不同无线网且IP以及用户名都相同

    问题现场及解析 用OpenSSH的人都知ssh会把你每个你访问过计算机的公钥(public key)都记录在~/.ssh/known_hosts. 当下次访问相同计算机时,OpenSSH会核对公钥. ...

  5. c++ 容器元素填充指定数量的元素(generate_n)

    #include <iostream> // cout #include <algorithm> // generate_n using namespace std; ; in ...

  6. Springboot 编码规范

    1.规范的意义和作用 编码规范可以最大限度的提高团队开发的合作效率 编码规范可以尽可能的减少一个软件的维护成本 , 并且几乎没有任何一个软件,在其整个生命周期中,均由最初的开发人员来维护 编码规范可以 ...

  7. Qt5.3.2_CentOS6.4_x86_调试源码关联【勿删,简洁】

    1. Qt5.3.2 --> Tools --> Options... --> 左侧选择"Debugger" --> 然后选择"General&q ...

  8. [原][OSG]深入osg函数----SceneView::cull 函数

    参考:最长一帧 先介绍几个类: osgUtil::CullVisitor:“筛选访问器” 当我们使用它遍历场景图形的各个节点时, CullVisitor 将会对每一个遇到的节点执行场景筛选的工作,判断 ...

  9. 《WAP团队》项目系统设计改进与详细设计

    任务1: 一.分析<基于家教管理系统项目需求规格说明书>初稿的不足,特别是文档需求描述建模不完整的内容. 通过软件工程更深入的学习发现我们的需求分析建模明显不足,缺少最重要的类图. 二.团 ...

  10. URAL 1513 Lemon Tale

    URAL 1513 思路: dp+高精度 状态:dp[i][j]表示长度为i末尾连续j个L的方案数 初始状态:dp[0][0]=1 状态转移:dp[i][j]=dp[i-1][j-1](0<=j ...