There are several way to solve it:
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.
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…