栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring之ORM模块代码详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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会自动维护这些对象

public interface ICatDao{ 
   public void createCat(Cat cat); 
   public List listCats(); 
   public int getCatsCount(); 
   public Cat findCatByName(String name); 
} 
import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 
public class CatDaoImpl extends HibernateDaoSupportimplements ICatDao{ 
   public void createCat(Cat cat){ 
this.getHibernateTemplate().persist(cat); 
   } 
   public List listCats(){ 
return this. getHibernateTemplate().find("select cfrom Cat c"); 
   } 
   public int getCatsCount(){ 
Number n = (Number)this.getSession(true).createQuery("selectcount(c) from Cat c").uniqueResult(); 
return n.intValue(); 
   } 
   public Cat findCatByName(String name){ 
List catList =this.getHibernateTemplate().find("select c from Cat where c.name = ?",name); 
if(catList.size()>0) 
   return catList.get(0); 
return null; 
   } 
  
} 
 
 
 
 
 
    
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层

public interface ICatService{ 
   public void createCat(Cat cat); 
   public List listCats();  
   public int getCatsCount(); 
} 

分层的做法是,程序调用Service层,Service层调用DAO层,DAO层调用Hibernate实现数据访问,原则上不允许跨曾访问。分层使业务层次更加清晰

public class CatServiceImpl implements ICatService{ 
   private IDao catDao; 
   public IDao getCatDao(){ 
return catDao; 
   } 
  
   public void setCatDao(IDao dao){ 
this.catDao = dao; 
   } 
    
   public void createCat(Cat cat){ 
catDao.createCat(cat); 
   } 
   public List listCats(){ 
return catDao.listCats(); 
   } 
   public int getCatsCount(){ 
return catDao.getCatsCount(); 
   } 
  
} 

然后再Service层配置事务管理

 
 
    
 
  
 
 
    
 
   PROPGATION_REQUIRED 
    
 
  
 
 
    
    
 
    
 
    
    
 

总结

以上就是本文关于Spring之ORM模块代码详解的全部内容,希望大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/142805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号