0

I am trying to utilize the following design for a class using the Spring Data, Hibernate, JPA frameworks. Note that the @GeneratedValue and @Id annoations are on different columns.

@Data
@Entity
@Table(name = "ACCTS")
public class MyAccount implements java.io.Serializable {


    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ACCOUNT_ID", nullable=false, precision=10, scale=0)
    private long accountId;

    @Id
    @Column(name="ACCOUNT_NUMBER", unique=true, nullable=false, precision=9, scale=0)
    private int accountNumber1;

    @Column(name="PRIMARY_NUMBER", nullable=false, precision=9, scale=0)
    private int accountNumber2;

}

The table looks like this. Note that the PRIMARY KEY constraint is not on the IDENTITY column.

CREATE TABLE CAACCTS (
    ACCOUNT_ID BIGINT  GENERATED BY DEFAULT AS IDENTITY ,
    ACCOUNT_NUMBER DECIMAL(9, 0) DEFAULT 0 NOT NULL ,
    PRIMARY_NUMBER DECIMAL(9, 0) DEFAULT 0 NOT NULL ,
    CONSTRAINT XXX PRIMARY KEY( ACCOUNT_NUMBER ) ) ;

This table can be created, but JPA seems to have trouble with the IDENTITY column - the identity values are never created. Additionally, if I try to do an update, I get a "DUPLICATE PRIMARY KEY" error.

Has anybody successfully done this (splitting the IDENTITY and PRIMARY KEY columns) with JPA and Hibernate?

user1071914
  • 3,295
  • 11
  • 50
  • 76
  • Maybe I don't understand your question. `@Id` designates the primary key. – Sotirios Delimanolis Jul 24 '13 at 19:45
  • 2
    This is not allowed in JPA, but is possible in other providers - EclipseLink allows specifying a return policy. Hibernate might have its own equivalent. I'm not sure the point though since the accountId will uniquely identify the entity, and so can be used as the ID. The ID can be different than the table's pk, as long as it is unique. – Chris Jul 24 '13 at 19:57
  • Yes, I know that this is crazy, this this the table structure I was given, though. Just trying to make it work (and not having much luck). – user1071914 Jul 24 '13 at 20:31
  • Even though each id is unique you can maybe call it a [composite primary key](http://stackoverflow.com/questions/14729206/jpa-table-with-2-primary-key-fields) and fool JPA, so long as they're both not-null and one of them is unique. – Pace Jul 24 '13 at 21:48
  • @Pace- unfortunately, not possible with HSQLDB. – user1071914 Jul 25 '13 at 02:26

1 Answers1

0

The short answer is "NO - this will not work." Logically, there is no reason to use an IDENTITY column except as part of a Primary Key, and this implementation does not work at all in JPA (at least, I was not able to get it to work.

In brief: AVOID.

user1071914
  • 3,295
  • 11
  • 50
  • 76