其主要是继承三个类:SQLFunction SqlUpdate MappingSqlQuery
操作步骤:
1、编写PersonFunction类,继承SqlFunction类并重写PersonFunction带参构造方法,传递参数为DataSource
public class PersonFunction extends SqlFunction {
public PersonFunction(DataSource ds){
super(ds,"select count(*) from person");// 计数,返回总共有多少条记录
compile();//以调用的方法,将父类注入并执行sql语句
}
}
public class PersonUpdate extends SqlUpdate {
public PersonUpdate(DataSource ds){
super(ds, "insert into person values(?,?,?)");
int[] types = {Types.INTEGER,Types.VARCHAR,Types.INTEGER};//必须指定各参数的类型TYPE,利用java.sql.Types类自定义的静态常量定义类型
setTypes(types);//调用父类的方法void setTypes(int[] types)将类型存放进去
compile();
}
}
public class PersonQuery extends MappingSqlQuery {
public PersonQuery(DataSource ds){
super(ds,"select * from person");
compile();
}
/*
* 与Person实体Bean映射
* 通过将结果集中各个字段的值,赋给Person属性的方式来映射
*/
@Override
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Person p = new Person();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAge(rs.getInt("age"));
return p;//返回对象
}
}
public interface ObjectPersonDao {
public List find();
public void update(Person p);
public int getCount();
}
public class ObjectPersonDaoImpl implements ObjectPersonDao{
private SqlFunction sf = null;
private SqlUpdate su = null;
private MappingSqlQuery msq = null;
public void setDataSource(DataSource ds){
sf = new PersonFunction(ds);
su=new PersonUpdate(ds);
msq = new PersonQuery(ds);
}
@Override
public List find() {
// TODO Auto-generated method stub
return msq.execute();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return sf.run();
}
@Override
public void update(Person p) {
// 传入参数
su.update(new Object[]{p.getId(),p.getName(),p.getAge()});
}
}
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@localhost:[1521]:adminwyd
scott
tiger
/**
* 1、SqlFunction执行Sql函数
* 2、SqlUpdate执行插入或者更新
* 3、MappingSqlQuery执行查询
* 4、上述三个类都是抽象类,需要继承并能实现
* @author wyd
*
*/
public class TestObjectJDBCTemplate {
public static void main(String[] args) {
ApplicationContext cpx = new ClassPathXmlApplicationContext("beans.xml");
ObjectPersonDao opd = (ObjectPersonDao) cpx.getBean("personDao");
Person person = new Person();
person.setId(60);
person.setName("AAA");
person.setAge(34);
opd.update(person);
List persons = opd.find();
System.out.println("数据数目:" + opd.getCount());
for (Iterator it = persons.iterator(); it.hasNext();) {
Person temp = (Person) it.next();
System.out.println("姓名:" + temp.getName() + "\t年龄:" + temp.getAge());
}
}
}
【P.S.】之前有朋友说,笔记虽然很全,但架不住不知道写哪儿。。。。。。o(╯□╰)o
所以我把源码上传为了资源,有兴趣的朋友可以去下载。