Separating JPA information from POJO

I am working on a project that will contain entities in a database using JPA. We will be using Maven as our project management framework. I am wondering if it is possible to create one project for a POJO and another to define persistence, and then "concatenate" the two into a single output containing the POJOs and their persistence information.

Basically I'm trying to decouple POJO code from persistence definition. Because POJOs can be reused by several different projects that may or may not need to save them and may or may not want to change the save information. (Similar, but not quite the same as Is it possible to build a JPA object by extending POJO? )

I have two ideas on how I can do this. If I was using POJO in a web application, I could provide persistence.xml and render the classes in that project and just add the dependency on the project that contains the POJO. But if I wanted to create a single jar file containing save and POJO information, I think I could use a shadow plugin?

Is there another way to essentially merge two maven projects into one output and is this a sane thing you want to do?

+3


source to share


2 answers


I appreciate the input. In the end, the solution for me was to create two projects. The first one gave the definition of POJO without any JPA info. Yes, there are some JPA related members like id, but I will refer to them. The second project contained JPA metadata (orm and persistence XML files).

In terms of persistence related members (like id), I could probably live with the ones in the model classes, but using the suggestion in this post ( Is it possible to build a JPA object by extending POJO? ) I extended POJO classes and declared an identifier in subclasses "entity". This requires some consideration when defining POJOs in terms of member access.



One note: this solution runs into problems when you have a class hierarchy (inheritance in your model). The classes in your "pure" model inherit from some generic class. This class is then extended in the "persistence" model to provide identifiers and other persistence-related members. Now, if persistent subclasses inherit from classes in the "pure" model, they do not inherit ID and other persistent members.

There can be workarounds in different inheritance mappings, such as a table for a specific class.

0


source


If I recall correctly, annotations do not have to be on the classpath if you are not using them. The annotated classes can still be loaded.

So my recommendation is:



  • Stick to JPA annotations as this is the simplest way to define mappings and tooling support is generally the best.
  • Declare JPA dependencies as optional and possibly also as...
  • If you need to override the mappings defined by annotations, it should be possible to do so using persistence.xml, AFAIK (never tried).
0


source







All Articles