简体   繁体   中英

Persisting third-party classes with no ID's

Say I have the following Java class, which is owned by a vendor so I can't change it:

public class Entry {
    private String user;
    private String city;

    // ...
    // About 10 other fields
    // ...

    // Getters, setters, etc.
}

I would like to persist it to a table, using JPA 2.0 (OpenJPA implementation). I cannot annotate this class (as it is not mine), so I'm using orm.xml to do that.

I'm creating a table containing a column per field, plus another column called ID . Then, I'm creating a sequence for it.

My question is: is it at all possible to tell JPA that the ID that I would like to use for this entity doesn't even exist as a member attribute in the Entry class? How do I go about creating a JPA entity that will allow me to persist instances of this class?

EDIT

I am aware of the strategy of extending the class and adding an ID property it. However, I'm looking for a solution that doesn't involve extending this class, because I need this solution to also be applicable for the case when it's not only one class that I have to persist, but a collection of interlinked classes - none of which has any ID property. In such a scenario, extending doesn't work out.

Eventually, I ended up doing the following:

public class EntryWrapper {
    @Id
    private long id;

    @Embedded
    private Entry entry;
}

So, I am indeed wrapping the entity but differently from the way that had been suggested. As the Entry class is vendor-provided, I did all its ORM work in an orm.xml file. When persisting, I persist EntryWrapper .

I don't have much experience with JPA, but I wouldn't extend your base classes, instead I would wrap them:

public class PersistMe<T> {

  @Id
  private long id;

  private T objToWrap;

  public(T objToWrap) {
    this.objToWrap = objToWrap;
  }
}

I can't test it, if it doesn't work let me know so I can delete the answer.

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