이 콘텐츠는 선택한 언어로 제공되지 않습니다.

1.2. Configuration


First, set up your classpath (after you have created a new project in your favorite IDE):
  • Copy all Hibernate3 core and required 3rd party library files (see lib/README.txt in Hibernate).
  • Copy hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your classpath as well.
If you wish to use Hibernate Validator, download it from the Hibernate website and add hibernate-validator.jar in your classpath.
If you wish to use Hibernate Search, download it from the Hibernate website and add hibernate-search.jar and lucene-core-x.y.z.jar in your classpath.
We also recommend a small wrapper class to start Hibernate in a static initializer block, known as HibernateUtil. You might have seen this class in various forms in other areas of the Hibernate documentation. For Annotation support you have to enhance this helper class as follows:
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()
                    configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log exception!
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession()
            throws HibernateException {
        return sessionFactory.openSession();
    }
}
Copy to Clipboard Toggle word wrap
Interesting here is the use of AnnotationConfiguration. The packages and annotated classes are declared in your regular XML configuration file (usually hibernate.cfg.xml). Here is the equivalent of the above declaration:
<!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 package="test.animals"/> <mapping class="test.Flight"/> <mapping class="test.Sky"/> <mapping class="test.Person"/> <mapping class="test.animals.Dog"/>
 <mapping resource="test/animals/orm.xml"/>
          </session-factory>
        </hibernate-configuration>
Copy to Clipboard Toggle word wrap
Note that you can mix the hbm.xml use and the new annotation one. The resource element can be either an hbm file or an EJB3 XML deployment descriptor. The distinction is transparent for your configuration process.
Alternatively, you can define the annotated classes and packages using the programmatic API
            sessionFactory = new AnnotationConfiguration() .addPackage("test.animals") //the fully qualified package name .addAnnotatedClass(Flight.class) .addAnnotatedClass(Sky.class) .addAnnotatedClass(Person.class) .addAnnotatedClass(Dog.class)
.addResource("test/animals/orm.xml")
      configure()..buildSessionFactory();
Copy to Clipboard Toggle word wrap
You can also use the Hibernate EntityManager which has its own configuration mechanism. Please refer to this project documentation for more details.
There is no other difference in the way you use Hibernate APIs with annotations, except for this start up routine change or in the configuration file. You can use your favorite configuration method for other properties ( hibernate.properties, hibernate.cfg.xml, programmatic APIs, etc). You can even mix annotated persistent classes and classic hbm.cfg.xml declarations with the same SessionFactory. You can however not declare a class several times (whether annotated or through hbm.xml). You cannot mix configuration strategies (hbm vs annotations) in a mapped entity hierarchy either.
To ease the migration process from hbm files to annotations, the configuration mechanism detects the mapping duplication between annotations and hbm files. HBM files are then prioritized over annotated metadata on a class to class basis. You can change the priority using hibernate.mapping.precedence property. The default is hbm, class, changing it to class, hbm will prioritize the annotated classes over hbm files when a conflict occurs.
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat