Home / Java Patterns and Pitfalls     frequal.com

JPA Configuration Tips

Setting up a new JPA-based web service, especially in a well-modularized maven project, can be tricky. Below are some of the possible issues I've run into after setting up many such projects.

Multiple persistence.xml Files

When assembling multiple JAR files into a WAR file, you may end up with multiple persistence.xml files in the WAR file. Due to the way the modules are split up, you may need persistence.xml in multiple JAR files. If they don't all match, you can end up with errors at runtime when Hibernate (or your JPA provider) scans the classpath and finds the wrong persistence.xml first. You'll see messages like
  org.hibernate.MappingException: Unknown entity
To solve, try to eliminate unneeded peristence.xml files. If you must have duplicates, make sure they all match and have all of your latest @Entity-annotated classes.

Right Class Names

Make sure the class names listed in persistence.xml are spelled correctly. Some IDEs can generate a list from your annotated Entity classes, which can help.

Matching Context

Double-check that your context name in persistence.xml matches what's in your code or configuration. Otherwise you may get messages like
 
  javax.persistence.PersistenceException: No Persistence provider for EntityManager named myname

Right Folder for persistence.xml

Perhaps it's obvious, but this just tripped me up recently. Make sure that persistence.xml is in src/main/resources/META-INF. If any one is misspelled (mine was 'resource'), it won't be included in the build artifacts and won't be available to JPA.
Last modified on 6 Jun 2021 by AO

Copyright © 2024 Andrew Oliver