Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

hibernate - JPA 2.0: Adding entity classes to PersistenceUnit *from different jar* automatically

I have a maven-built CDI-based Java SE app, which has a core module, and other modules.
Core has the persistence.xml and some entities. Modules have additional entities.

How can I add the entities to the spotlight of the persistence unit?

I have read Hibernate manual, http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/configuration.html#setup-configuration-packaging

I have also seen these SO questions

I am looking for a solution where Hibernate would scan for all loaded classes, or, would pick up some config file form the other jars (like e.g. CDI does with beans.xml).

My app does not use Spring. I don't insist on portability - I'll stick with Hibernate.

  • Is there some such solution?
  • Is there's a way to create a PU from persistence.xml and add classes to it programmatically?
  • Can I add @Entity classes to EntityManagerFactory after it was created?

Update: I found in org.?hibernate.?ejb.?Ejb3Configuration:

public Ejb3Configuration configure(String persistenceUnitName, Map integration)  

http://docs.jboss.org/hibernate/entitymanager/3.6/javadocs/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several way to solve it:

  1. As described in Do I need <class> elements in persistence.xml?, you can set hibernate.archive.autodetection property and Hibernate should be able to look up all annotated classes from classpath. However, that's not JPA spec compliant.

  2. If you are using Spring, from Spring 3.1.2 (or probably even a bit earlier), in LocalContainerEntityManagerFactoryBean, you can define packageToScan which will ask LocalContainerEntityManagerFactoryBean to scan in classpath to find all annotated classes. Again, not JPA spec compliant.

  3. I was using Maven as build tools. Years before, I have written a little plugin which will generate persistence.xml during build process. The plugin will scan from build classpath to find out all annotated classes, and list them in the generated persistence.xml. This is most tedious but the result is JPA spec compliant. One drawback (which does not apply to most people I believe) is the lookup happens in build-time, not runtime. That means if you are having an application for which entities JARs are provided only at deploy/runtime but not build time, this approach is not going to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...