hibernate 4.3.x - load all entity annotated classes

久未见 提交于 2019-12-01 17:25:17
peter.petrov

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 call
ClassPath.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!