Search code examples
javajakarta-eeentityjpa-2.0entity-relationship

How to use the @TableGenerator annotation for a non-PK id


This is an extract of the JPA entities schema



    @Entity
    @Table(name="customer")
    public class Customer implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="customer_id")
        private Long id;

        @ManyToOne
        @JoinColumn(name="company_id",nullable=false)
        private Company company;

    //...

    }

    @Entity
    @Table(name="company")
    public class Company implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="company_id")
        private Long id;

    //...

    }

    @Entity
    @Table(name="order_header")
    public class OrderHeader implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="order_id")
        private Long id;


        @ManyToOne
        @JoinColumn(name="customer_id",nullable=false)
        private Customer customer;

        private Long internalCompanyOrderId;

    //...

    }

I need to retreive an unique internalCompanyOrderId sequence for each Company_id. It means that nevertheless the Order PK will be 'order_id', I need an "internal" order_id for each Company.


Solution

  • There is no occurrences of @TableGenerator in your code sample. I assume you want to generate value with @GeneratedValue.

    What it comes to JPA 2.0, according specification you cannot use @GeneratedValue for field that is not part of the primary key:

    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]
    ...
    [97] Portable applications should not use the GeneratedValue annotation on other persistent fields or properties.