王朝网络
分享
 
 
 

hibernate配置笔记

王朝java/jsp·作者佚名  2006-01-09
宽屏版  字体: |||超大  

一个配置的例子:

1.先在数据库中建立一个表cat

create table cat(

cat_id varchar(20) PRIMARY KEY not null,

name varchar(20) not null,

sex char(1))

2.建立hibernate.cfg.xml并生成hibernaetFactory.class管理他

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 2.0//EN"

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

<!-- DO NOT EDIT: This is a generated file that is synchronized -->

<!-- by MyEclipse Hibernate tool integration. -->

<hibernate-configuration>

<session-factory>

<!-- properties -->

<property name="connection.username">root</property>

<property name="connection.url">jdbc:mysql://localhost:3306/test</property>

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

<property name="connection.password"></property>

<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>

<!-- mapping files -->

<mapping resource="com/mdcl/vo/Cat.hbm.xml"/>

</session-factory>

</hibernate-configuration>

HibernaetFactory.java

package com.mdcl.hibernate;

import net.sf.hibernate.HibernateException;

import net.sf.hibernate.Session;

import net.sf.hibernate.cfg.Configuration;

/**

* Configures and provides access to Hibernate sessions, tied to the

* current thread of execution. Follows the Thread Local Session

* pattern, see {@link http://hibernate.org/42.html}.

*/

public class HibernateFactory {

/**

* Location of hibernate.cfg.xml file.

* NOTICE: Location should be on the classpath as Hibernate uses

* #resourceAsStream style lookup for its configuration file. That

* is place the config file in a Java package - the default location

* is the default Java package.<br><br>

* Examples: <br>

* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".

* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>

*/

private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

/** Holds a single instance of Session */

private static final ThreadLocal threadLocal = new ThreadLocal();

/** The single instance of hibernate configuration */

private static final Configuration cfg = new Configuration();

/** The single instance of hibernate SessionFactory */

private static net.sf.hibernate.SessionFactory sessionFactory;

public static Session currentSession() throws HibernateException {

Session session = (Session) threadLocal.get();

if (session != null && !session.isOpen()) session = null;

if (session == null) {

if (sessionFactory == null) {

try {

cfg.configure(CONFIG_FILE_LOCATION);

sessionFactory = cfg.buildSessionFactory();

} catch (Exception e) {

System.err

.println("%%%% Error Creating HibernateSessionFactory %%%%");

e.printStackTrace();

}

}

session = sessionFactory.openSession();

threadLocal.set(session);

}

return session;

}

public static void closeSession() throws HibernateException {

Session session = (Session) threadLocal.get();

threadLocal.set(null);

if (session != null) {

session.close();

}

}

private HibernateFactory() {

}

}

3.建立cat表的po(持久对象),生成cat.cfg.xml,cat.java,AbstractCat.java的过程和上面生成hibernate.cfg.xml和hibernateFactory.java的过程可以由myeclipse协助完成。

cat.cfg.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->

<!-- by MyEclipse Hibernate tool integration. -->

<!-- Created Sat Feb 19 12:00:50 CST 2005 -->

<hibernate-mapping package="com.mdcl.vo">

<class name="Cat" table="cat">

<id name="catId" column="cat_id" type="java.lang.String">

<generator class="uuid.hex"/>

</id>

<property name="name" column="name" type="java.lang.String" not-null="true" />

<property name="sex" column="sex" type="java.lang.String" />

</class>

</hibernate-mapping>

cat.java

/*

* Created Thu Feb 17 16:11:44 CST 2005 by MyEclipse Hibernate Tool.

*/

package com.mdcl.vo;

import java.io.Serializable;

/**

* A class that represents a row in the 'cat' table.

* This class may be customized as it is never re-generated

* after being created.

*/

public class Cat extends AbstractCat implements Serializable

{

/**

* Simple constructor of Cat instances.

*/

public Cat()

{

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#getCatId()

*/

public String getCatId() {

// TODO Auto-generated method stub

return super.getCatId();

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#getName()

*/

public String getName() {

// TODO Auto-generated method stub

return super.getName();

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#getSex()

*/

public String getSex() {

// TODO Auto-generated method stub

return super.getSex();

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#getWeight()

*/

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#setCatId(java.lang.String)

*/

public void setCatId(String catId) {

// TODO Auto-generated method stub

super.setCatId(catId);

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#setName(java.lang.String)

*/

public void setName(String name) {

// TODO Auto-generated method stub

super.setName(name);

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#setSex(java.lang.String)

*/

public void setSex(String sex) {

// TODO Auto-generated method stub

super.setSex(sex);

}

/* (non-Javadoc)

* @see com.mdcl.vo.AbstractCat#setWeight(java.lang.Integer)

*/

/* (non-Javadoc)

* @see java.lang.Object#hashCode()

*/

public int hashCode() {

// TODO Auto-generated method stub

return super.hashCode();

}

/* (non-Javadoc)

* @see java.lang.Object#finalize()

*/

protected void finalize() throws Throwable {

// TODO Auto-generated method stub

super.finalize();

}

/* (non-Javadoc)

* @see java.lang.Object#clone()

*/

protected Object clone() throws CloneNotSupportedException {

// TODO Auto-generated method stub

return super.clone();

}

/* (non-Javadoc)

* @see java.lang.Object#equals(java.lang.Object)

*/

public boolean equals(Object obj) {

// TODO Auto-generated method stub

return super.equals(obj);

}

/* (non-Javadoc)

* @see java.lang.Object#toString()

*/

public String toString() {

// TODO Auto-generated method stub

return super.toString();

}

/**

* Constructor of Cat instances given a simple primary key.

* @param catId

*/

public Cat(java.lang.String catId)

{

super();

}

/* Add customized code below */

}

AbstractCat.java

/*

* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized

* by MyEclipse Hibernate tool integration.

*

* Created Sat Feb 19 12:00:50 CST 2005 by MyEclipse Hibernate Tool.

*/

package com.mdcl.vo;

import java.io.Serializable;

/**

* A class that represents a row in the cat table.

* You can customize the behavior of this class by editing the class, {@link Cat()}.

* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration.

*/

public abstract class AbstractCat

implements Serializable

{

/** The cached hash code value for this instance. Settting to 0 triggers re-calculation. */

private int hashValue = 0;

/** The composite primary key value. */

private java.lang.String catId;

/** The value of the simple name property. */

private java.lang.String name;

/** The value of the simple sex property. */

private java.lang.String sex;

/**

* Simple constructor of AbstractCat instances.

*/

public AbstractCat()

{

}

/**

* Constructor of AbstractCat instances given a simple primary key.

* @param catId

*/

public AbstractCat(java.lang.String catId)

{

this.setCatId(catId);

}

/**

* Return the simple primary key value that identifies this object.

* @return java.lang.String

*/

public java.lang.String getCatId()

{

return catId;

}

/**

* Set the simple primary key value that identifies this object.

* @param catId

*/

public void setCatId(java.lang.String catId)

{

this.hashValue = 0;

this.catId = catId;

}

/**

* Return the value of the name column.

* @return java.lang.String

*/

public java.lang.String getName()

{

return this.name;

}

/**

* Set the value of the name column.

* @param name

*/

public void setName(java.lang.String name)

{

this.name = name;

}

/**

* Return the value of the sex column.

* @return java.lang.String

*/

public java.lang.String getSex()

{

return this.sex;

}

/**

* Set the value of the sex column.

* @param sex

*/

public void setSex(java.lang.String sex)

{

this.sex = sex;

}

/**

* Implementation of the equals comparison on the basis of equality of the primary key values.

* @param rhs

* @return boolean

*/

public boolean equals(Object rhs)

{

if (rhs == null)

return false;

if (! (rhs instanceof Cat))

return false;

Cat that = (Cat) rhs;

if (this.getCatId() != null && that.getCatId() != null)

{

if (! this.getCatId().equals(that.getCatId()))

{

return false;

}

}

return true;

}

/**

* Implementation of the hashCode method conforming to the Bloch pattern with

* the exception of array properties (these are very unlikely primary key types).

* @return int

*/

public int hashCode()

{

if (this.hashValue == 0)

{

int result = 17;

int catIdValue = this.getCatId() == null ? 0 : this.getCatId().hashCode();

result = result * 37 + catIdValue;

this.hashValue = result;

}

return this.hashValue;

}

}

4.编写一个例子测试一下

servletTest.java

/*

* Created on 2005-2-19

*

* TODO To change the template for this generated file go to

* Window - Preferences - Java - Code Style - Code Templates

*/

package com.mdcl.test;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import net.sf.hibernate.HibernateException;

import net.sf.hibernate.Session;

import net.sf.hibernate.Transaction;

import org.apache.log4j.Logger;

import com.mdcl.hibernate.HibernateFactory;

import com.mdcl.vo.Cat;

/**

* @author a

*

* TODO To change the template for this generated type comment go to

* Window - Preferences - Java - Code Style - Code Templates

*/

public class servletTest extends HttpServlet {

/**

* Destruction of the servlet. <br>

*/

private static Logger log=Logger.getLogger(servletTest.class);

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet. <br>

*

* This method is called when a form has its tag value method equals to get.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request,response);

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has its tag value method equals to post.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out

.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<HTML>");

out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");

out.println(" <BODY>");

out.print(" This is ");

out.print(this.getClass());

try {

log.info("........servletTest.doPost()....start");

Session session =HibernateFactory.currentSession();

Transaction tx = session.beginTransaction();

Cat cat = new Cat();

cat.setCatId("4");

cat.setName("Karl");

cat.setSex("F");

session.save(cat);

tx.commit();

} catch (HibernateException e) {

e.printStackTrace();

log.error("........servletTest.doPost()....error");

}

log.debug("start");

out.println(", using the POST method");

out.println(" </BODY>");

out.println("</HTML>");

out.flush();

out.close();

log.info("........servletTest.doPost()....end");

}

/**

* Initialization of the servlet. <br>

*

* @throws ServletException if an error occure

*/

public void init() throws ServletException {

// Put your code here

}

}

好了,完成了一次hibernate旅行。不求甚解?

参考由曹晓刚等人翻译的hibernate中文文档

hibernate中文站点www.hibernate.org.cn

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
>>返回首页<<
推荐阅读
 
 
频道精选
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
© 2005- 王朝网络 版权所有