JPA Composite Key + Sequence

Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence?

This is my composite class:

public class IntegrationEJBPk implements Serializable {


    @ManyToOne(cascade = {}, fetch = FetchType.EAGER)
    @JoinColumn(name = "APPLICATION")
    public ApplicationEJB getApplication() {
        return application;

    @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true)
    public String getEntity() {
        return entity;

    @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN")
    @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ")
    @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true)
    public String getCanonicalId() {
        return canonicalId;

    @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true)
    public String getNativeId() {
        return nativeId;

    @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true)
    public String getNativeKey() {
        return nativeKey;


I already supply the values for application, entity, nativeId and nativeKey. I want to construct an entity like the one below:

IntegrationEJB i1 = new IntegrationEJB();
i1.setIntegrationId(new IntegrationEJBPk());

And when I call em.persist(i1), I want that the canonicalId is generated and the integration is inserted.

Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).

Asked by: Lily969 | Posted: 28-01-2022

Answer 1

I believe that this is not possible with plain JPA.

Answered by: Fenton790 | Posted: 01-03-2022

Answer 2

Using @GeneratedValue for composite PKs is not specified withi JPA 2 spec.

From the JPA spec:

11.1.17 GeneratedValue Annotation

The GeneratedValue annotation provides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.[97] The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the GeneratedValue annotation is not supported for derived primary keys.

Note that under a different scenario, you can have a parent entity with a simple PK (@Id) that uses @GeneratedValue, and then have a child entity that has a composite PK that includes the generated Id from the parent, plus another column.

  • Give the child a @ManyToOne relationship to the parent entity, so that it inherits the generated ID in a FK column.
  • Then give the child a composite PK, via @IdClass specified against the entity, plus two @Id columns within the entity.
public class ParentEntity {
       @GenerateValue(IDENTITY) // If using DB auto-increment or similar
       int id;

       // ...
public class ChildEntity {
   // The child table will have a composite PK:
   // (parent_ID, child_name)
       int parentEntity;
       String childName;

       String favoriteColor;  // plus other columns

       // ...

// child Id attributes have the same name as the child entity
// however the types change to match the underlying PK attributes 
// (change ParentEntity to int)
 public class ChildId implements Serializable {
        int parentEntity;
        String childName;

        public ChildId() { //... }

        // Add extra constructor & remove setter methods so Id objects are immutable
        public ChildId(int parentEntity, String childName) { //... }

        public int getParentEntity() { //... }
        // make Id objects immutable:
        //  public void setParentEntity(int parentEntity) { //... }
        public String getChildName() { //... }
        //  public void setChildName(String childName) { //... }

Answered by: Sydney971 | Posted: 01-03-2022

Answer 3

Try like this:

@TableGenerator(name = "canonicalKeys", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "canonicalKeys")
@Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true)
public String getCanonicalId() {
    return canonicalId;

In this way instead of using a sequence you can use a table.

Answered by: Robert525 | Posted: 01-03-2022

Answer 4

I notice that it appears your building a composite primary key like this example. While I was poking at a similar problem in my own database I wondered if maybe you could call the sql directly like:

select nextval ('hibernate_sequence')

I suppose that would be cheating though ;-)

Answered by: Carlos329 | Posted: 01-03-2022

Similar questions

java - JPA Composite Key WITH Sequence in spring boot JPA

Is it possible in plain JPA or Hibernate a composite key, where an element of the composite key is a sequence and the other element is a mapped with a foreign key. I have a composite key in my table and part of it needs to be generated by a sequence. I tried the following, but it doesn't work class produit @Entity public class Produit{ @EmbeddedId private ProduitClientPK id=new Produit...

java - Find composite location on screen

I am implementing a on screen keyboard in Java for SWT and AWT. One important thing is to move the keyboard to a position where the selected text field can show and is not lying behind the on screen keyboard. For AWT i can detect the position of the current selected component with Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) { return...

java - Why does an SWT Composite sometimes require a call to resize() to layout correctly?

Sometimes we encounter an SWT composite that absolutely refuses to lay itself out correctly. Often we encounter this when we have called dispose on a composite, and then replaced it with another; although it does not seem to be strictly limited to this case. When we run into this problem, about 50 % of the time, we can call pack() and layout() on the offending composite, and all will be w...

java - Jpa composite key nullable columns

I'm using Hibernate's JPA impl to model some tables. I'm having trouble mapping a table that: Has no primary key Has a unique index on 4 columns, 3 of which can be nullable I tried to hack it and define the index as a composite Id, but since some columns are nullable this is not working properly. Is this possible with JPA/Hibernate? Thanks

java - HQL: How to sort list of objects on property of mapped composite element

I have an object with a map of components: <class name="Article" table="articles"> ... <map name="i18nData" table="articles_i18n"> <key column="id" not-null="true"/> <map-key column="language" type="string"/> <composite-element class="Article$ArticleI18nData"> <property name="displayName" type="string"/> </composite-element> ...

Composite Strategy pattern - java - How bad is this code?

This question is kind of continuation to my earlier post: Visitor pattern implementation in java- How does this look? I got a bit confused while refactoring my code. I am trying to convert my visitor pattern (explained in the prior post) into a composite strategy pattern. I am trying to do something li...

java - Should I use composite primary keys or not?

There seems to only be 2nd class support for composite database keys in Java's JPA (via EmbeddedId or IdClass annotations). And when I read up on composite keys, regardless of language, people keep coming across as them being a bad thing. But I cannot understand why. Are composite keys still acceptable to use these days? If not, why not? I've found one person who agrees with me:

java - What is the best way to represent a composite key (key containing two values) of a Class and a Boolean

HashMap<Pair<Class<T>,Boolean>,String> abc = new HashMap<Pair<Class<T>,Boolean>,String>(); What is the best way to represent Pair here... Does Java offer anything? My key will always be a {class,boolean} pair. Thanks!

java - SWT composite - redraw problem

I have a composite element, that initially has a Label. Now I call dispose on the it (the label) and create another label in the same container (composite elm), but I don't see the new text. It brings me to question how do I enable redraw on the composite, so that the new label (or any other component I might create) will render in place of the old one. Here is the code I have (separated into a unit test for redraw a compo...

java - How to create Composite object without parent?

I'm writing a project in Java using SWT. I would like to create a temporary container for some controls. How would I create a composite control without a parent object?

java - parent child relation in composite object?

I have a composite object (tree) with parent-child relationships.The tree can be upto n levels (say for e.g 10-12 levels) Now suppose i have to remove an object at level 6 in the hierarchy.If i point its reference to null (while leaving the child object untouched) in Java then what happens to the child objects under it (do they become available for garbage collection).

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)