问题
In a project which I work on I don't use Spring, I use Hibernate only. I don't want to use hbm.xml files for entity mappings/descriptions/etc. I want to use annotations only.
How do I tell Hibernate to load all Entity/Table
annotated classes from certain package(s)?
I searched on the web but I have no luck. Also I don't find information about the latest Hibernate version (mostly outdated articles/posts/etc.).
Edit 1:
http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#mapping
The hibernate doc page says this:
Object/relational mappings can be defined in three approaches:
1) using Java 5 annotations (via the Java Persistence 2 annotations)
2) using JPA 2 XML deployment descriptors (described in chapter XXX)
3) using the Hibernate legacy XML files approach known as hbm.xml
So that's it, I just want to use 1) with the SessionFactory/Session Hibernate API.
Edit 2:
Even though my questions was marked as duplicate, it's not, because I don't want to use JPA (and the implied descriptors) but just approach 1) from those listed above.
回答1:
OK, this is not possible in Hibernate 4.3.x and was never possible it seems.
See also this question/answer (even though this post is old, it's quite valid):
Add Annotated Class in Hibernate by adding all classes in some package. JAVA
1) After I did some research on this, it seems it's a common misconception that Configuration.addPackage
allows us to load all entity classes from a given package. It's not true. I found it the hard way by looking in the hibernate sources and only then I found the above SO question/answer which confirmed it. In fact I am not quite sure what addPackage
does, but it doesn't seem very useful for my case.
2) Seems one thing we can do is to call Configuration.addAnnotatedClass
for each of our own annotated entity classes e.g. by hard-coding those classes at compile time. Or ... alternatively by using Reflections or Guava we can find all (i.e. our own) entity classes from a given package dynamically at runtime, loop through them, and still call Configuration.addAnnotatedClass
. The only problem with Reflections is that it comes with quite a few dependencies of its own. So we have to add 9 new JARs for this simple thing (what a pain) if we decide to use Reflections. With Guava it's somewhat easier, we can just callClassPath.from
(
Thread.currentThread().getContextClassLoader()
).
getTopLevelClasses(pckg)
.
If anyone has a better approach - feel free to provide it.
I will accept the best answer, not necessarily my answer.
来源:https://stackoverflow.com/questions/28097847/hibernate-4-3-x-load-all-entity-annotated-classes