Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Hibernate: is it possible to mix Annotations and XML configuration for an Entity?

So, is possible to mix both configurations instead of use only one of those?

All I want is to keep all the configuration by Annotations and read the table by a XML.

Is it possible?

Thanks a lot.

Edit: How will be the hbm.xml file? I have this one:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="MyData" table="MyTable" >
    </class>
</hibernate-mapping>

And don´t compile the dtd.

like image 509
ganzux Avatar asked Dec 27 '11 09:12

ganzux


People also ask

How do I override hibernate annotation based configuration?

One way to do this is using JPA XML configuration to override the existing class annotations. However, JPA does not support generic generators, which is a requirement due to the structure of our legacy database.

What are the 2 configuration files in hibernate?

There is the two way of mapping in hibernate – The first one which is by using the hibernate annotation and the second one which is by using the hbm. xml.

What is XML configuration in hibernate?

These configurations contain the mapping information that provides different functionalities to Java classes. Generally, we provide database related mappings in the configuration file. Hibernate facilitates to provide the configurations either in an XML file (like hibernate. cfg.

What is entity annotation in hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.


1 Answers

Hibernate docs (latest)

Note that you can mix the legacy hbm.xml use and the annotation approach. The resource element can be either an hbm file or an EJB3 XML deployment descriptor. The distinction is transparent for your configuration process.

You can 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 an 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 and changing it to class, hbm will prioritize the annotated classes over hbm files when a conflict occurs.

like image 141
viktor Avatar answered Sep 20 '22 03:09

viktor