服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

hibernate初体验cat之快速上手

  hibernate的手册里的cat例子感觉很不明了,很难照着它轻松的运行起第一个例子,费了点周折,总算看到一点结果,如果你是新手,可以参考一下,少走一些弯路。

  1.下载tomcat和hibernate

  tomcat 5.0.27 | tomcat 5.0.28 | hibernate2.1.6

  2. 安装

  以tomcat+mysql+hibernate为例

  tomcat的安装,及mysql的安装和dbcp的配制参见

  http://blog.csdn.net/ahxu/archive/2004/09/01/91611.aspx,这里就不提了,这里假设tomcat+mysql已经配置并测试可用,这里%webapp%代表你已配置好的一个web应用的root,着重说一下hibernate的安装,

  1) 解压下载的压缩包,将解压出来的hibernate2.jar复制到%webapp%/web-inf/lib

  2) 将解压出来的lib目录下的

  cglib-full-2.0.2.jar
  commons-collections-2.1.1.jar
  commons-logging-1.0.4.jar
  dom4j-1.4.jar
  ehcache-0.9.jar
  jta.jar
  log4j-1.2.8.jar
  odmg-3.0.jar

  文件同样复制到%webapp%/web-inf/lib,具体请参见解压出来的lib目录下的readme.txt。

  3) 将解压出来的etc目录下的
  log4j.properties

  文件复制到%webapp%/web-inf/classes。

  3.编写相关文件

  1) 按照参考文档,配置hibernate,将以下代码保存为hibernate.cfg.xml放在%webapp%/web-inf/classes下


  <?xml version='1.0' encoding='utf-8'?>
  <!doctype hibernate-configuration
  public "-//hibernate/hibernate configuration dtd//en"
  "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
  <hibernate-configuration>

  <session-factory>

 






  <property name="connection.datasource">java:comp/env/jdbc/mysql</property>
  <property name="show_sql">false</property>
  <property name="dialect">net.sf.hibernate.dialect.mysqldialect</property>

  <!-- mapping files -->
  <mapping resource="cat.hbm.xml"/>

  </session-factory>

  </hibernate-configuration>


  

  note:这里与hibernate文档里的不一样,这里指定数据源为mysql数据库jdbc/mysql,方言dialect为net.sf.hibernate.dialect.mysqldialect。

  2) 将以下代码保存为cat.java,并生成相应的cat.class,放入%webapp%/web-inf/classes,这里无论你用什么方法生成cat.class,但最终cat.class应在%webapp%/web-inf/classes/net/sf/hibernate/examples/quickstart目录下


  package net.sf.hibernate.examples.quickstart;
  public class cat {

  private string id;
  private string name;
  private char sex;
  private float weight;

  public cat() {
  }

  public string getid() {
  return id;
  }

  private void setid(string id) {
  this.id = id;
  }

  public string getname() {
  return name;
  }

  public void setname(string name) {
  this.name = name;
  }

  public char getsex() {
  return sex;
  }

 






  public void setsex(char sex) {
  this.sex = sex;
  }

  public float getweight() {
  return weight;
  }

  public void setweight(float weight) {
  this.weight = weight;
  }

  }

 

  3) 将以下代码保存为o/r映射文件cat.hbm.xml,放入%webapp%/web-inf/classes


  <?xml version="1.0"?>
  <!doctype hibernate-mapping
  public "-//hibernate/hibernate mapping dtd//en"
  "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
  <hibernate-mapping>
  <class name="net.sf.hibernate.examples.quickstart.cat" table="cat">
  <!-- a 32 hex character is our surrogate key. it's automatically
  generated by hibernate with the uuid pattern. -->
  <id name="id" type="string" unsaved-value="null" >
  <column name="cat_id" sql-type="char(32)" not-null="true"/>
  <generator class="uuid.hex"/>
  </id>
  <!-- a cat has to have a name, but it shouldn' be too long. -->
  <property name="name">
  <column name="name" length="16" not-null="true"/>
  </property>
  <property name="sex"/>
  <property name="weight"/>
  </class>
  </hibernate-mapping


  

  4) 在数据库内建表,结构如下

  column |         type          | modifiers
  --------+-----------------------+-----------
  cat_id | character(32)         | not null
  name   | character varying(16) | not null
  sex    | character(1)          |
  weight | real                  |
  indexes: cat_pkey primary key btree (cat_id)
  





  5) 将以下代码保存为hibernateutil.java,并生成相应的hibernateutil.class,放入%webapp%/web-inf/classes,同样注意package


  package net.sf.hibernate.examples.quickstart;
  import org.apache.commons.logging.log;import org.apache.commons.logging.logfactory;
  import net.sf.hibernate.*;
  import net.sf.hibernate.cfg.*;
  public class hibernateutil {

  private static log log = logfactory.getlog(hibernateutil.class);

  private static final sessionfactory sessionfactory;

  static {
  try {
  // create the sessionfactory
  sessionfactory = new configuration().configure().buildsessionfactory();
  } catch (throwable ex) {
  log.error("initial sessionfactory creation failed.", ex);
  throw new exceptionininitializererror(ex);
  }
  }

  public static final threadlocal session = new threadlocal();

  public static session currentsession() throws hibernateexception {
  session s = (session) session.get();
  // open a new session, if this thread has none yet
  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();
  }
  }

 

  note:这里与hibernate文档也不同,原文档编绎时缺少2个包,这里已加上。





  6) 将以下代码保存为test.jsp,放入%webapp%/,用http测试


  <%@ page language="java" pageencoding="gb2312" %><%@ page import="net.sf.hibernate.transaction"%><%@ page import="net.sf.hibernate.session"%><%@ page import="net.sf.hibernate.cfg.*"%><%@ page import="net.sf.hibernate.query"%><%@ page import="net.sf.hibernate.examples.quickstart.hibernateutil"%><%@ page import="net.sf.hibernate.examples.quickstart.cat"%><%@ page import="java.util.*"%><!doctype html public "-//w3c//dtd html 4.0 transitional//en"><html><head><title>lomboz jsp</title></head><body bgcolor="#ffffff">
  <%
  //添加一只cat

  session ses = hibernateutil.currentsession();
  transaction tx= ses.begintransaction();

  cat princess = new cat();
  princess.setname("ahxu");
  princess.setsex('f');
  princess.setweight(7.4f);

  ses.save(princess);
  tx.commit();

  hibernateutil.closesession();

  //读取库里所有cat

  ses = hibernateutil.currentsession();
  tx= ses.begintransaction();

  query query = ses.createquery("select c from cat as c where c.sex = :sex");
  query.setcharacter("sex", 'f');
  for (iterator it = query.iterate(); it.hasnext();) {
  cat cat = (cat) it.next();
  out.println("female cat: " + cat.getname() );
  }

  tx.commit();
  hibernateutil.closesession();
  %>
  </body>
  </html>

 

  小结

  步骤基本与原文档步骤相同,只是做了一些补充,方便上手,这里并没有对其中的一些配置做具体解释,如有疑问请参见发行包中的相关文档。

  以上tomcat5.027 + hibernate2.1.6测试通过





扫描关注微信公众号