Java Reference
In-Depth Information
Using Annotations in Your Application
You will need to install the Hibernate 3 annotations toolset, available from the Hibernate
annotations page ( http://annotations.hibernate.org ). If you do not already use JDK 5.0, you
will need to upgrade to take advantage of the native support for annotations.
n Tip If you want to declare your mappings inline with your source code, but cannot use a Java 5 environ-
ment, the XDoclet tool allows you to use javadoc-style comments to achieve a similar effect. XDoclet can be
obtained from http://xdoclet.sourceforge.net .
Your application needs the hibernate-annotations.jar and ejb3-persistence.jar files
provided in the annotations toolset.
If you are using a hibernate.cfg.xml file to establish the mapping configuration, you will
need to provide the fully qualified name of the annotated class with the <mapping> element:
<mapping class="com.hibernatebook.annotations.Book"/>
When you are configuring the SessionFactory , you will need to make use of an
AnnotationConfiguration object instead of the Configuration object used with XML map-
pings, as follows:
SessionFactory factory =
new AnnotationConfiguration().configure().buildSessionFactory();
If you prefer to configure the mappings manually rather than through the hibernate.
cfg.xml file, you can do this through the AnnotationConfiguration object, as follows:
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Book.class);
SessionFactory factory = config.configure().buildSessionFactory();
If you need to use your annotated entities from within an EJB 3 container, you must use
the standard EntityManager instead of the Hibernate-specific Session . Hibernate provides an
implementation of EntityManager as a separate download. At the time of writing, this is still a
beta version, but as it closely follows the state of the EJB 3 specification, you should have little
trouble migrating code from the current implementation over to any final release (or to third-
party EntityManager s). See Appendix A for details of how to use the Hibernate EntityManager .
EJB 3 Persistence Annotations
In Chapter 3, we walked you through the creation of a very simple application using the basic
XML mapping files—annotations might have been simpler, but as already noted, only Java 5
users would be able to use an annotation-based example.
When you develop using annotations, you start with a Java class, and then annotate the
source code listing with metadata notations. In J2SE 5.0, the Java Runtime Environment ( JRE)
parses these annotations. Hibernate uses Java reflection to read the annotations and apply the
Search WWH ::




Custom Search