Sara
Sara

Reputation: 71

Defining entity in Hibernate 4

I am just starting in Hibernate 4 and I'm noticing that they're are two ways to define an entity. Either by defining an xml file hbm and map it with a bean or instead just define a bean and use annotation for mapping with the table in DB like (@Entity, @column.. etc).

My question is what's the difference between both methods ? Sorry if the question is simple but I couldn't find my answer online..

Thanks for the help

Upvotes: 1

Views: 623

Answers (2)

xea
xea

Reputation: 1214

The biggest difference is how you approach Hibernate. Some may prefer XML configurations over annotations and vica versa.

Using the XML configuration gives you greater control over Hibernate and lets you keep your configuration files in one place.

On the other hand JPA Annotations allows a more intuitive persistence configuration while keeping your business logic free of vendor lockins.

You may want to check this thread too.

Upvotes: 1

Bozhidar Batsov
Bozhidar Batsov

Reputation: 56645

Using the annotations you're binding your model (entities) to the Hibernate framework fairly tightly (you're introducing coupling between them). On the other hand your source code becomes much more readable since you don't have to switch forth between the XMLs and the Java sources files.

Originally Hibernate supported only the XML mappings and annotations were added later (after they were introduced in Java 5). Most Java developers favor heavily the annotations since they really make it apparent that a class represents a Hibernate entity, what constraints it has and how it relates to other entities in the application. On the other hand using the XML definitions decouples your source from Hibernate and you can easily switch to another library without modifying the Java sources. You'd do much better with the use of the Java Persistence API and it's portable annotations, though. It give to the ability to use an unified ORM API that can delegate to any ORM framework (Hibernate, ibatis, EclipseLink, etc). Switching between frameworks is easy as changing on line in JPA's configurations and adding the new ORM to your projects classpath. In practice very few companies use Hibernate directly (unless they need some of its unique features) - its generally used in combination with JPA. Very few people use the XML entity definitions as well - I haven't worked on a project with them in quite a while.

Upvotes: 3

Related Questions