HibernateDaoSupport与JdbcDaoSupport总结
Spring中Dao 的支持类可以有好多,如: JdbcDaoSupport , HibernateDaoSupport ,JdoDaoSupport等,下面对最常用的HibernateDaoSupport与JdbcDaoSupport做一小总结:
1、借助类JdbcDaoSupport的简约化实现:
借助这个类不需要HIbernate框架,也不需要有ORM的对象关联映射。但它和HibernateDaoSupport很类似,有JdbcTemplate来实现增、删、改、查操作。
public class PersonDaoJdbcTest {public static void main(String[] args) throws Exception {ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");PersonDao pd=(PersonDao) ctx.getBean("persondao");pd.createPerson(new PersonBean("abdaslf",34));System.out.println(pd.findPersonsByName("yan"));System.out.println("finished!");}}public class PersonDaoJdbc extends JdbcDaoSupport implements PersonDao{public void createPerson(PersonBean p) throws Exception {Object[] args={p.getName(),new Integer(p.getAge())};this.getJdbcTemplate().update("insert into person(p_name,p_age) values(?,?)", args);}public void deletePerson(int id) throws Exception {Object [] args={new Integer(id)};this.getJdbcTemplate().update("delete from person where id=?",args);}}public List findPersonsByName(String name) throws Exception {// TODO Auto-generated method stubreturn this.getJdbcTemplate().query("select * from person where p_name like '%"+name+"%'", new PersonRowMapper());}
需要在Spring的配置文件applicationContext.xml中控制反转用到连接数据库中的类是注入DataSource,如下:
applicationContext.xml:
<!-- 数据源配置 --><bean id="dataSource"value="root"></property><property name="password" value="123456"></property></bean> <bean id="persondao" "+u.getEmail());
???? }
}
public static void main(String[] args) {
?????????? ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
?????????? TestA t = (TestA)ctx.getBean("testa");
?????????? t.test();
}
}
需要在Spring的配置文件applicationContext.xml中控制反转用到连接数据库中的类是注入SessionsFactory,如下:
applicationContext.xml:
??????? <bean id="testa" class="com.sun.demo.TestA">
??????? <property name="sessionFactory">
??????? <ref bean="mySessionFactory"/>
??????? </property>
??????? </bean>