JPA/Hibernate and composite keys

2019-02-10 18:29发布

问题:

I have come across some SO discussions and others posts (e.g. here, here and here) where using composite primary keys with JPA is described either as something to be avoided if possible, or as a necessity due to legacy databases or as having "hairy" corner cases. Since we are designing a new database from scratch and don't have any legacy issues to consider is it recommended or let's say, safer, to avoid composite primary keys with JPA (either Hibernate or EclipseLink?).

My own feeling is that since JPA engines are complex enough and certainly, like all software, not without bugs, it may be best to suffer non-normalized tables than to endure the horror of running against a bug related to composite primary keys (the rationale being that numeric single-column primary keys and foreign keys are the simplest use case for JPA engines to support and so it should be as bug-free as possible).

回答1:

I've tried both methods, and personally I prefer avoiding composite primary keys for several reasons:

  • You can make a superclass containing the id field, so you don't have to bother with it in all your entities.
  • Entity creation becomes much easier
  • JPA plays nicer in general
  • Referencing to an entity becomes easier. For example storing a bunch of IDs in a set, or specififying a single id in the query string of a web page is largelly simplified by only having to use a single number.
  • You can use a single equals method specified in the super class that works for all entities).
  • If you use JSF you can make a generic converter
  • Easier to specify objects when working with your DB client

But it brings some bad parts aswell:

  • Small amount of denormalization
  • Working with unpersisted objects (if you use auto generated IDs, which you should) can mean trouble in some cases, since equality methods and such needs an ID to work correctly