网友提供的hibernate 的一个范例

本文分享了一个基于Hibernate框架的简单实例,展示了如何通过Struts和Tomcat搭建环境,并使用Hibernate进行基本的增删查改操作。代码示例包括实体类、DAO层、Hibernate工具类及Struts集成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近这一个阶段一直在研究hibernate,总感觉好象什么地方特别扭,研究一段时间,看了论坛上的各位大虾和小虾写的例子,自己也写了一个,在这里贴出来,希望得到大家的批评指正,特别是在架构上如何设计给些意见,因为对照关系如一对一,一对多的实现论坛的例子已经很清楚了.  

开发环境:  
struts  1.1  
tomcat4.1.24  
hibernate2.1.2  
oracle  8.16  

表﹕company  

id  公司ID  
company_name  公司名稱  

配置就不說了﹐  

po:company.java  
java代码:    

public  class  Company  {  
               private  String  id;  
               private  String  companyname;  
               
               public  String  getId(){  
                               return  id;  
               }  
               public  String  getCompanyname(){  
                               return  companyname;  
               }  
               
               public  void  setId(String  id){  
                               this.id=id;  
               }  
               public  void  setCompanyname(String  companyname){  
                               this.companyname=companyname;  
               }  
}
 


company持久類對應的映射文件﹕  
company.hbm.xml  

java代码:    

<?xml  version="1.0"?>  

<!DOCTYPE  hibernate-mapping  PUBLIC  
       "-//Hibernate/Hibernate  Mapping  DTD  2.0//EN"  
       "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">  

<hibernate-mapping>  
       <class  name="com.foxconn.hibernate.po.Company"  table="company"  dynamic-update="false">  
               <id  name="id"  column="id"  type="string"  unsaved-value="any"  >  
                       <generator  class="assigned">  
                       </generator>  
               </id>  
               <property  name="companyname"  type="string"  update="true"  insert="true"  column="company_name"/>  
       </class>  
</hibernate-mapping>
 


配置文件hibernate.cfg.xml  
java代码:    

<!DOCTYPE  hibernate-configuration  PUBLIC  "-//Hibernate/Hibernate  Configuration  D  

TD//EN"  "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">  

<hibernate-configuration>  

<session-factory>  

<property  name="connection.datasource">java:comp/env/jdbc/fox221</property>  

<property  name="show_sql">false</property>  

<property  name="dialect">net.sf.hibernate.dialect.OracleDialect</property>  

<property  name="jdbc.fetch_size">50</property>  

<property  name="jdbc.batch_size">30</property>  

<!--  Mapping  files  -->  

<mapping  resource="/hbm/Company.hbm.xml"/>  

</session-factory>  

</hibernate-configuration>
 


提供session的类HebernateSessionFactory(利用Thread管理session)  

java代码:    

public  class  HibernateSessionFactory  {  
       public  static  final  ThreadLocal  session  =  new  ThreadLocal();  
       private  static  SessionFactory  sessionFactory;  

         static  {  
               try  {  
                       sessionFactory  =  
                                       new  Configuration().configure().buildSessionFactory();  
               }  catch  (HibernateException  ex)  {  
                       throw  new  RuntimeException(  
                                       "Exception  building  SessionFactory:  "  +  ex.getMessage(),ex);  
               }  
       }  

       public  static  Session  currentSession()  throws  HibernateException{  
                               Session  s  =  (Session)  session.get();  
                               if  (s  ==  null)  {  
                                       s  =    sessionFactory.openSession();  
                                       session.set(s);  
                               }  
                               return  s;  
       }  
       public  static  void  closeSession()  throws  HibernateException{  
               Session  s  =  (Session)  session.get();  
               session.set(null);  
               if  (s  !=  null)  s.close();  
       }  
       
}
 


封装CRUD操作的类(我觉的此类应该设置为abstract类)  
java代码:    

public  class  HibernateUtil  {  
       public  static  void  add(  Object  object  )throws  HibernateException{                Session  s  =  HibernateSessionFactory.currentSession();  
               s.save(  object  );  
               s.flush();  
               s.beginTransaction().commit();  
       }  
       public  static  void  update(  Object  object  )  throws  HibernateException  {  
               Session  s  =  HibernateSessionFactory.currentSession();  
               s.beginTransaction();  
               s.saveOrUpdate(  object  );  
               s.flush();  
       }  
       public  static  void  remove(Class  clazz,  String  id)  throws  HibernateException  {  
               Session  s  =  HibernateSessionFactory.currentSession();  
               s.beginTransaction();  
               Object  object  =  s.load(clazz,  id);  
               s.delete(  object  );  
               s.flush();  
       }  
       public  static  Object  findById(  Class  clazz,  String  id  )  throws  HibernateException  {  
               Object  obj  =  null;  
               Session  s  =  HibernateSessionFactory.currentSession();  
               obj  =  s.load(  clazz,  id  );  
               s.flush();  
               return  obj;  
       }  
}
 


在filter中关闭session,这个filter还可以用于字符集转换.  
HibernateFilter.java  

java代码:    

public  class  HibernateFilter  implements  Filter  {  
     private  String  encode  =  "big5";  
       
       public  void  init(FilterConfig  config)  {  
               this.encode  =  config.getInitParameter("encode");  
       }  

       public  void  doFilter(ServletRequest  request,  ServletResponse  response,  FilterChain  chain)  {  
               try{  
                       request.setCharacterEncoding(this.encode);  
                       response.setContentType("text/html;charset="+encode);  
                       chain.doFilter(request,  response);  
               }  
               catch(Exception  e){  
                       if(!(e  instanceof  java.net.SocketException)){  
                               if(request  instanceof  HttpServletRequest)  
                                       Logger.getLogger(this.getClass()).error("error  request  uri:"+((HttpServletRequest)request).getRequestURI());  
                               Logger.getLogger(this.getClass()).error(e);  
                       }  
               }finally{  
                               try{  
                                               HibernateSessionFactory.closeSession();  
                               }catch(Exception  ex){  
                                               System.out.println("Error  in  closing  session");  
                               }                
               }  
       }  

       public  void  destroy()  {  
       }  
}
 

以上是hibernate相关部分.

companyDAO.java  是个接口.  

java代码:    

public  interface  CompanyDAO  {  
               public  void  addCompany(Company  company)  throws  HibernateException;  
}
 


工厂类HibernateDAOFactory.java  
java代码:    

public  class  HibernateDAOFactory  implements  DAOFactory{  
       public  static  Object  getInstance(String  subClassName)  throws  
               ClassNotFoundException,  
               InstantiationException,  
               IllegalAccessException{  
               return  (Class.forName(subClassName).newInstance());  
       }  
}
 


DAO的实现类CompanyDAOImpl  
java代码:    

public  class  CompanyDAOImpl  implements  CompanyDAO{  

               public  void  addCompany(Company  company)  throws  HibernateException{  
                                                               HibernateUtil.add(company);  
               }  

}
 


struts的action类只负责控制转发CompanyAction.java  
java代码:    

public  class  CompanyControl  extends  DispatchAction{  

               public  ActionForward  saveCompany(ActionMapping  mapping,ActionForm  form  ,HttpServletRequest  request,HttpServletResponse  response)  throws  Exception{  
                       HttpSession  session  =  request.getSession();  
                       
                       String  id=request.getParameter("id");  
                       String  name=request.getParameter("name");  
                       
                       Company  company=new  Company();  
                       company.setId(id);  
                       company.setCompanyname(name);  
                       
                       CompanyDAO  companyDAO=(CompanyDAO)HibernateDAOFactory.getInstance("CompanyDAOImpl");  
                       companyDAO.addCompany(company);  
                       
                       return  mapping.findForward("success");  
       }                
}
 
下面是相关的两个页面.index.jsp和保存后成功页面success.jsp  

index.jsp  

<%@  page  contentType="text/html;  charset=Big5"  %>  
<%@  taglib  uri="/WEB-INF/struts-tiles.tld"  prefix="tiles"  %>  
<%@  taglib  uri="/WEB-INF/struts-logic.tld"  prefix="logic"  %>  
<%@  taglib  uri="/WEB-INF/struts-html.tld"  prefix="html"  %>  
<%@  taglib  uri="/WEB-INF/struts-bean.tld"  prefix="bean"  %>  

<html:html>  
<head>  
<link  href="<%=  request.getContextPath()  %>/style/SelfCss.css"  rel="stylesheet"  type="text/css">  
</head>  
<body>  
<html:form  action="company.do?action=saveCompany">  
<table>  
<tr>  
<td>Company  ID:</td>  
<td><html:text  property="id"  /></td>  
</tr>  
<tr>  
<td>Company  Name:</td>  
<td><html:text  property="name"  /></td>  
</tr>  
<tr>  
<td><html:submit  value="submit"  /></td>  
<td><html:reset  value="reset"/></td>  
</tr>  
</table>  
</html:form>  
</body>  
</html:html>  

success.jsp  此画面用来输出成功插入的信息!  

<html:html>  
<body>  
Successful!!!  
</body>  
</html:html> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值