Spring之ORM模块代码详解
Spring框架七大模块简单介绍
Spring中MVC模块代码详解
ORM模块对Hibernate、JDO、TopLinkiBatis等ORM框架提供支持
ORM模块依赖于dom4j.jar、antlr.jar等包
在Spring里,Hibernate的资源要交给Spring管理,Hibernate以及其SessionFactory等知识Spring一个特殊的Bean,有Spring负责实例化与销毁。因此DAO层只需要继承HibernateDaoSupport,而不需要与Hibernate的API打交道,不需要开启、关闭Hibernate的Session、Transaction,Spring会自动维护这些对象
publicinterfaceICatDao{
publicvoidcreateCat(Catcat);
publicListlistCats();
publicintgetCatsCount();
publicCatfindCatByName(Stringname);
}
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
publicclassCatDaoImplextendsHibernateDaoSupportimplementsICatDao{
publicvoidcreateCat(Catcat){
this.getHibernateTemplate().persist(cat);
}
publicListlistCats(){
returnthis.getHibernateTemplate().find("selectcfromCatc");
}
publicintgetCatsCount(){
Numbern=(Number)this.getSession(true).createQuery("selectcount(c)fromCatc").uniqueResult();
returnn.intValue();
}
publicCatfindCatByName(Stringname){
ListcatList=this.getHibernateTemplate().find("selectcfromCatwherec.name=?",name);
if(catList.size()>0)
returncatList.get(0);
returnnull;
}
}
com.clf.spring.orm.Cat com.clf.spring.orm.Dog org.hibernate.dialect.MySQLDialect true true create
如果使用XML配置的实体类,则改为
……
classpath:/com/clf/orm/Cat.hbm.xml
Spring默认在DAO层添加事务,DAO层的每个方法为一个事务。Spring+Hibernate编程中,习惯的做法实在DAO层上再添加一个Service层,然后把事务配置在Service层
publicinterfaceICatService{
publicvoidcreateCat(Catcat);
publicListlistCats();
publicintgetCatsCount();
}
分层的做法是,程序调用Service层,Service层调用DAO层,DAO层调用Hibernate实现数据访问,原则上不允许跨曾访问。分层使业务层次更加清晰
publicclassCatServiceImplimplementsICatService{
privateIDaocatDao;
publicIDaogetCatDao(){
returncatDao;
}
publicvoidsetCatDao(IDaodao){
this.catDao=dao;
}
publicvoidcreateCat(Catcat){
catDao.createCat(cat);
}
publicListlistCats(){
returncatDao.listCats();
}
publicintgetCatsCount(){
returncatDao.getCatsCount();
}
}
然后再Service层配置事务管理
PROPGATION_REQUIRED
总结
以上就是本文关于Spring之ORM模块代码详解的全部内容,希望大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!