简体   繁体   中英

JAXB Factory for JPA entities

In most of my previous projects I have two domain models, one with JAXB annotations and the other one with JPA annotations. I know they can combined into one model with both annotations in the same class, but in my experiences the tradeoffs with this approach always came to the conclusion to separate them. Another advantage of a separate approach is the ability to create the JAXB classes with a XSD and easily link in XSDs from other projects.

In most cases I need factory classes being able for flexible creation of JAXB representations of my entities, eg

public class UserFactory
{
  public UserFactory(User queryUser, String lang)
  {
     this.queryUser=queryUser;
     this.lang=lang;
  }

  public JaxbUser getUser(JpaUser jpaUser)
  {
     JaxbUser jaxbUser = new JaxbUser();

     if(queryUser.isSetId()){jaxbUser.setId(jpaUser.getId());}
     if(queryUser.isSetEmail()){jaxbUser.setEmail(jpaUser.getEmail());}

     if(queryUser.isSetRoles())
     {
       RolesFactory f = new RolesFactory(queryUser.getRoles(),lang);
       jaxbUser.setRoles(f.getRoles(jpaUser.getRoles()));
     }
     return jaxbUser;
  }
}

I create a UserFactory with an individual template queryUser and the desired lang for entities supporting different languages. The template is checked during creation of the result for specific fields or additional factories and the resulting object is created. The query is defined in a XML file like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<query lang="en">
  <user id="1">
    <roles>
      <role code="code"/>
    </roles>
  </user>
</query>

With this methodology I have a powerful and flexible tool to create customized XML, despite all drawback of maintaining two domain models and the factory classes. I know there are many frameworks or libraries available which I never have heard about, so here my question:

Is there something available similar to my approach?

There are basically two options:

  • JPA and JAXB annotations on the same classes (see Hyperjaxb3 or DataNucleus )
  • Or you keepm the separated and write code to map one onto another

I personally do not see much added value in the cross-model mapping code. Usage of factories also does not seem too innovative, it is just a question of programming technique which you use to map one onto another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM