跨向Hibernate(二)

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

重新在Eclipse下再来过一遍,步骤有些不同。(eclipse+myEclipse)

1、创建一个普通的Java项目

2、加入用myeclipse导入Hibernate的包

3、加入MySql的JDBC包(应该先在myeclipse中配置数据库的服务)

4、创建一下数据POJO(忘了是不是这么叫,先这么写着吧)

5、在项目根结点用右键,查看项目属性,在Myeclipse-hibernate中添加(标准)Standard Hibernate包

6、在项目根结点用右键,运行myeclipse中的run-XDocLet,生成POJO的hbm文件

7、在项目根结点用右键,运行myeclipse中的add Hibernate Capabilities …(这个功能好象只能使用一次)

在向导中a、加入数据库的接入方式b、加入POJO的hbm文件c、可指定一个目录自动生成一个SessionFactory类

8、创建一个测试类,运行;例如:

public class Test {

public static void main(String[] args) throws HibernateException {

Session aSession = HibernateSessionFactory.currentSession();

Transaction tx=aSession.beginTransaction();

Cat cat=new Cat();

cat.setName("Tomcat");

cat.setSex("T");

cat.setWeight(12.1);

aSession.save(cat);

tx.commit();

HibernateSessionFactory.closeSession();

}

}

附:

可以看到,前前后后总共就只创建了两个类,其他全部自动生成。

要特别说明的是,POJO中一定要加入XDoclet的标签,不然Hibernate会怠工,hbm文件是生成不出来的。示例如下:

/*

* Created on 2005-4-26

*

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

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

*/

package com.hibernate.test;

/**

* @author julysea

*

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

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

*/

/**

* @hibernate.class

* table="cat"

*/

public class Cat {

String cat_id;

String name;

String sex;

double weight;

public Cat() {

}

/**

* @hibernate.id

* column = "cat_id"

* unsaved-value = "true"

* generator-class = "uuid.hex"

* @return Returns the cat_id.

*/

public String getId() {

return cat_id;

}

/**

* @param cat_id The cat_id to set.

*/

public void setId(String cat_id) {

this.cat_id = cat_id;

}

/**

* @hibernate.property

* @return Returns the name.

*/

public String getName() {

return name;

}

/**

* @param name The name to set.

*/

public void setName(String name) {

this.name = name;

}

/**

* @hibernate.property

* @return Returns the sex.

*/

public String getSex() {

return sex;

}

/**

* @param sex The sex to set.

*/

public void setSex(String sex) {

this.sex = sex;

}

/**

* @hibernate.property

* @return Returns the weight.

*/

public double getWeight() {

return weight;

}

/**

* @param weight The weight to set.

*/

public void setWeight(double weight) {

this.weight = weight;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有