论坛首页 Java版 Hibernate

十分钟在jb里面运行hibernate的简单例子。

浏览 39845 次
该帖已经被评为精华帖
作者 正文
时间:2003-10-15
终于有点对hibernate入门的感觉。方便门外的学习者,给一个简单的入门例子。
如果你有用过其他持久架构 转到hibernate其实很简单。一些原理方面就不讲了,
robbin讲的肯定比我好的多,自己去精华版看看。
我所给的只是我当初刚开始接触hibernate时候很想要的一个简单例子和设置方法。
一直没有找到,所以现在放到这里给大家看看,(只给想要入门的一个直观的感应,呵呵)

首先当然要新建一个项目

然后在Project Properties->Paths->Required Libraries->add->new 这里定义hibernate的类库 把hibernate的lib下面的所有jar包进去 当然还有hibernate2.jar也要
然后一路ok下去就可以了。

再来就是hibernate.properties
从hibernate的src下面找到
把它拷到你项目的src目录下
(什么,你的项目没有src目录,新建一个随便的类就有src目录了)

这样一个JB下面的hibernate的开发环境就好了

然后在hibernate.properties里面设置你的数据库连接
默认是HypersonicSQL

嗯 接下来的是你最想要做的事情了 其实很简单
新建一个类Message.java
代码如下

[code:1]package hello;

import java.io.Serializable;

/**
* @author getdown
* @version 1.0
*/

public class Message implements Serializable {
private Long id;
private String text;
//定义一个简单链表 指向另外的一个Message
private Message nextMessage;
public Message() {}

public Message(Long id) {
this.id = id;
}

public Message(String text) {
this.text = text;
}

public Message(Long id, String text) {
this.id = id;
this.text = text;
}

public Long getId() {
return id;
}

private void setId(Long id) {
this.id = id;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public Message getNextMessage() {
return nextMessage;
}

public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}

}[/code:1]
接下来是这个类对应的hibernate的配置文件 Message.hbm.xml

[code:1]<?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="hello.Message"
table="Messages"
>
<!--定义ID字段和生成ID的策略 这里采用identity-->
<id name="id"
column="MESSAGE_ID"
>
<generator class="identity"/>
</id>
<!--定义里面的text字段-->
<property
name="text"
type="string">
<!--定义text字段在数据库里面生成的方法-->
<column
name="TEXT"
length="100"
not-null="true"
/>
</property>
<!--定义对象关联之间的对应关系和关联的字段-->
<many-to-one
name="nextMessage"
cascade="all"
column="NEXT_MESSAGE_ID"
/>
</class>
</hibernate-mapping>[/code:1]
然后就是测试类

[code:1]package hello;

import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import net.sf.hibernate.Session;
import net.sf.hibernate.Query;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.type.LongType;
import net.sf.hibernate.Transaction;



/**
* @author getdown
* @version 1.0
*/

public class Hello {
public Hello() {
}

public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration().addClass(Message.class);

/** 顾名思义 构建表。。。第一次运行的时候运行下面语句可以在数据库生成表
* 之后可以把下面这句去掉
* */
// new SchemaExport(cfg).create(true, true);

//先生成sessionFactory
SessionFactory sessions = cfg.buildSessionFactory();
//再从sessionFactory得到一个session
Session session = sessions.openSession();
//启动事务
Transaction tx = session.beginTransaction();

//开始对数据库的操作
/*----对数据库的创建操作--------*/
Message message = new Message("helloWorld");
//创建一条记录

session.save(message);
//存入记录
session.flush();
//提交事务
tx.commit();


/*---对数据库的查询操作---------------*/
// Message message = new Message();
// Query q = session.createQuery("from Message as message where message.id=1");
// message = (Message) q.list().get(0);
// message.getNextMessage().setText("helloNext");
// session.flush();
// session.close();
// Long id = new Long(1);
// Message message = (Message) session.find("from Message as message where message.id=?", id, Hibernate.LONG).get(0);
// System.out.println(message.getText());


// /*-------事务的处理----------------*/
// try {
// Message message = new Message("hello");
// session.save(message);
// session.flush();
// message = new Message("hello");
// session.save(message);
// session.flush();
// tx.commit();
// }
// catch (HibernateException ex) {
// tx.rollback();
// }

/*-------添加1000条记录时间--------------*/
// long start = System.currentTimeMillis();
// for(int i = 0; i < 1000; i ++) {
// Message message = new Message("hello");
// session.save(message);
// session.flush();
// }
// tx.commit();
// long end = System.currentTimeMillis();
// System.out.println("添加1000条记录时间---" + (end-start)/1000 + "s");



session.close();


}

}[/code:1]
ok了 运行一下Hello看看出来什么吧
怎么样 比起CMP的持久 hibernate的持久是不是显得很轻量级。。
还可以试试看hibernate的性能 把Hello.java的最后一段注释去掉运行看看

当然hibernate最重要的还是它的原理,还有很多很好的,很有趣的功能和O/RM设计思想等着你自己发掘。
多看看它自己的文档,可以学到很多东西,它的文档真的非常好。


呵呵 我是刚刚接触hibernate不久 和所有hibernate的学习者共同学习
msn : java_xml@msn.com
   
时间:2003-10-16
只要把Message.hbm.xml建在和你的Message.java相同的目录就可以

编译或者运行的时候jb会自动copy到class里面Message.class相同的目录
   
0 请登录后投票
时间:2003-10-16
你的库表结构是什么样子的?
nextmessage和message是什么关系?
hbn.xml里面是many to one的关系?
   
0 请登录后投票
时间:2003-10-16
看看Message.hbm.xml就很清楚了:

MESSAGE_ID BIGINT
TEXT VARCHAR(100)
NEXT_MESSAGE_ID BIGINT

就一个表自己关联
   
0 请登录后投票
时间:2003-10-18
to dmhorse:
引用
问题1.请问如何解决,如果在左边树中,选取webapp的属性,在classes选项添加classes,虽然添加了,但老是不在Project source显示出来


选中上面的**/** 下面的include class dependense

引用
问题2.按hibernate文档,既可以用hib....cfg.xml也可用hib....pro这种设置connection,我用了hib...pro这种,运行期在叫找不到hi...cfg.xml
到底是是否是两个配置文件选其一,还是都必需


配置文件当然只要一个就可以了 可以用properties文件 也可以用xml文件
如果要在struts加plugin的话用xml文件


引用
问题3.出现上面情况,估计是在classpath不能找到那个hib....pro文件,但我的pro文件确实放在D:/tomcat/webapps/hib/WEB-INF/classes
请问如何在jb中设定classpath,在linux or dos下我都会,但来到jb就不懂了

project properties -> path -> required Libraries 就是jb的classpath

引用
问题4.楼上经常说将xml设为copy,请问在哪设啊?是File types include那设吗?

propect properties - > build -> resource

实在不大想回答这些问题 呵呵 很多配置方面的问题自己多试试看就可以出来了
即使配不成功也可以大致对IDE的功能有所了解
   
0 请登录后投票
时间:2003-10-18
Query q = session.createQuery("from Message as message where message.id=1");

这里的sql语句什么意思,我怎么看不懂,特别是as message ???
   
0 请登录后投票
时间:2003-10-18
乱发帖子有罪吗?
   
0 请登录后投票
时间:2003-10-18
错能改过还是没罪的 哈哈哈
   
0 请登录后投票
时间:2003-10-23
这个例子我拷贝了一份,配置后运行正常。我将添加操作的语句加了进去,运行程序后,发现数据库中只有三条记录,运行时间大约5秒。调试发现,操作执行了,但是循环语句部分的数据并没有添加到数据库中去,,并且多次运行后,数据库中还是只有三条记录。请帮忙看看:

运行平台:
MSSQL2000 + Hibernate2.1beta + windows2000

数据库配置如下:
hibernate.dialect net.sf.hibernate.dialect.SybaseDialect
hibernate.connection.username sa
hibernate.connection.password 535353
## Microsoft Driver (not supported!)
hibernate.connection.driver_class com.microsoft.jdbc.sqlserver.SQLServerDriver
hibernate.connection.url jdbc:microsoft:sqlserver://10.64.30.61:1433;DatabaseName=sm_middle


运行后的消息如下:

警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to sm_middle
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将数据库上下文改为 'sm_middle'。
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC]Language changed to 简体中文
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:25 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将语言设置改为 简体中文。
2003-10-23 22:05:25 net.sf.hibernate.connection.DriverManagerConnectionProvider close



警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC]Database changed to sm_middle
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将数据库上下文改为 'sm_middle'。
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC]Language changed to 简体中文
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: SQL Warning: 0, SQLState:
2003-10-23 22:05:31 net.sf.hibernate.util.JDBCExceptionReporter logWarnings
警告: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]已将语言设置改为 简体中文。
添加1000条记录时间---5s


修改变化部分如下:
[quote] Transaction tx = session.beginTransaction();
try {
message = new Message("hello");
session.save(message);
session.flush();
message = new Message("hello");
session.save(message);
session.flush();
tx.commit();
message = new Message("hello");
session.save(message);
session.flush();
}
catch (HibernateException ex) {
tx.rollback();
}

/*-------添加1000条记录时间--------------*/
// Message message;
long start = System.currentTimeMillis();
for(int i = 0; i < 1000; i ++) {
message = new Message("hello" + i);
session.save(message);
session.flush();
}
long end = System.currentTimeMillis();
System.out.println("添加1000条记录时间---" + (end-start)/1000 + "s");
session.close();[/quote]
[[b][/b][/quote]
   
0 请登录后投票
时间:2003-10-23
补充一下,数据库的驱动程序是Microsoft的。
整个sql的执行过程如下:
修改表的约束-->删除表格-->创建表-->修改表的约束-->增加记录

我通过事件跟踪器跟踪,发现插入sql语句确实执行了。但数据库表中却只有三条记录,即循环部分的插入sql没有提交
   
0 请登录后投票
论坛首页 Java版 Hibernate

跳转论坛:
JavaEye推荐