Hibernate 4.3.x - load all annotated feature classes

In the project I'm working on, I do not use Spring, I use only Hibernate. I do not want to use hbm.xml files for entity mappings / descriptions / etc. I want to use only annotations.

How do I tell Hibernate to load all Entity/Table annotated classes from specific packages?

I searched on the Internet, but I was out of luck. Also, I do not find information about the latest version of Hibernate (mostly outdated articles / posts / etc.).

Change 1:

http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#mapping

The hibernate doc page says the following:

Object-relational mappings can be defined in three approaches:
1) using Java 5 annotations (via Java Persistence 2 annotations)
2) using JPA 2 XML deployment descriptors (described in chapter XXX)
3) using a subset of the Hibernate XML files known as hbm.xml

So, I just want to use 1) with the SessionFactory / Session Hibernate API.

Edit 2:

Despite the fact that my questions were marked as duplicates, this is not so, because I do not want to use JPA (and implied descriptors), but just approach 1) of the ones listed above.

+5
source share
1 answer

OK, this is not possible in Hibernate 4.3.x and has never been possible.

See also this question / answer (even if this post is old, this is quite true):
Add annotated class to Hibernate by adding all classes to some package. Java

1) After I did some research on this, it seems a common misconception that Configuration.addPackage allows us to load all entity classes from this package. It is not true. I found this the hard way by looking at the sources of sleep mode, and only then did I find the above question / answer that confirmed it. Actually, I'm not quite sure what addPackage does, but that doesn't seem very useful for my case.

2) It seems that we can only make a call to Configuration.addAnnotatedClass for each of our own annotated entity classes, for example. by hard coding these classes at compile time. Or ... alternatively, using Reflections or Guava , we can find all (that is, our own) entity classes from a given package dynamically at run time, skip them and still call Configuration.addAnnotatedClass . The only problem with Reflections is that it comes with quite a few dependencies. Therefore, we must add 9 new JARs for this simple thing (what a pain) if we decide to use Reflections. With Guava, this is somewhat simpler, we can just call ClassPath.from ( Thread.currentThread().getContextClassLoader() ). getTopLevelClasses(pckg) ClassPath.from ( Thread.currentThread().getContextClassLoader() ). getTopLevelClasses(pckg) .

If anyone has a better approach, feel free to provide one.
I will answer the best answer, not necessarily my answer.

+6
source

Source: https://habr.com/ru/post/1211726/


All Articles