Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
EJB3 and Hibernate Annotations 学习笔记(一)

作者:未知 来源:月光软件站 加入时间:2005-6-5 月光软件站

借助JDK 5.0的新特性Annotations,你可以使用它代替先前使用的XDoclet,不过当且仅当使用JDK 5.0的时候,为了保持向下兼容,用XDoclet生成mapping files仍然是最好的选择。

首先建立环境,将hibernate-annotations.jarlib/ejb-3.0-edr2.jar复制到你的CLASSPATH下。

官方的建议是将Hibernate初始化放在static块内,建立如下的HibernateUtils类以方便使用。
package hello;

import org.hibernate.*;
import org.hibernate.cfg.*;
import test.*;
import test.animals.Dog;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {

sessionFactory = new AnnotationConfiguration()

.addPackage("test")
.addAnnotatedClass(Flight.class)
.addAnnotatedClass(Sky.class)
.addAnnotatedClass(Person.class)
.addAnnotatedClass(Dog.class)

.buildSessionFactory();
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
}

public static Session getSession()
throws HibernateException {
return sessionFactory.openSession();
}
}
这里有趣的地方就是使用AnnotationConfiguration并且声明包名和用于持久化的类名。当然你也可以在xml配置文件中加入。

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping resource="test/Boat.hbm.xml"/>
<mapping package="test"/>
<mapping class="test.Flight"/>
<mapping class="test.Sky"/>
<mapping class="test.Person"/>
<mapping class="test.animals.Dog"/>

</session-factory>
</hibernate-configuration>

这是一个不错的选择,你可以将hbm文件和annotation影射混合使用。
还有一个问题就是子类不能在父类之前被配置,看下面的例子:

cfg.addAnnotatedClass(Animal.class);
cfg.addAnnotatedClass(Dog.class); // OK

cfg.addAnnotatedClass(Dog.class);
cfg.addAnnotatedClass(Animal.class); // AnnotationException!
这里Dog是Animal的子类。

(未完待续)



相关文章

相关软件