Search code examples
jpaeclipselinkcomposite-primary-key

JPA - Real primary key generated ID for references


I have ~10 classes, each of them, have composite key, consist of 2-4 values. 1 of the classes is a main one (let's call it "Center") and related to other as one-to-one or one-to-many.

Thinking about correct way of describing this in JPA I think I need to describe all the primary keys using @Embedded / @PrimaryKey annotations.

Question #1: My concern is - does it mean that on the database level I will have # of additional columns in each table referring to the "Center" equal to number of column in "Center" PK?

If yes, is it possible to avoid it by using some artificial unique key for references? Could you please give an idea how real PK and the artificial one needs to be described in this case?

Note: The reason why I would like to keep the real PK and not just use the unique id as PK is - my application have some data loading functionality from external data sources and sometimes they may return records which I already have in local database. If unique ID will be used as PK - for new records I won't be able to do data update, since the unique ID will not be available for just downloaded ones. At the same time it is normal case scenario for application and it just need to update of insert new records depends on if the real composite primary key matches.

Question #2: All of the 10 classes have common field "date" which I described in an abstract class which each of them extends. The "date" itself is never a key, but it always a part of composite key for each class. Composite key is different for each class. To be able to use this field as a part of PK should I describe it in each class or is there any way to use it as is? I experimented with @Embedded and @PrimaryKey annotations and always got an error that eclipselink can't find field described in an abstract class.

Thank you in advance!

PS. I'm using latest version of eclipselink & H2 database.


Solution

  • See,

    http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Composite_Primary_Keys

    For info on composite keys.

    Normally using a single generated id is better, but if you have legacy data you can use a composite key.

    I would not recommend using an @EmbeddedId, instead use an @IdClass, it is much simpler. EclipseLink does not require the @IdClass, but if you wish to use find() then you need one to compose the key values.

    You should be able to use a @MappedSuperclass do define one of the id fields, ensure you annotate each key field with @Id.

    EclipseLink does allow using the @PrimaryKey annotation to simplify specifying a composite key, you just need to give the list of columns. You still must map those columns to attribute in your class.