javasqloracle-databasehibernateora-01400

Compound Primary Key in Hibernate using Annotations


I have a table which uses two columns to represent its primary key, a transaction id and then the sequence number.

I tried what was recommended http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping in section 2.2.3.2.2, but when I used the Hibernate session to commit this Entity object, it leaves out the TXN_ID field in the insert statement and only includes the BA_SEQ field!

What's going wrong? Here's the related code excerpt:

@Id 
@Column(name="TXN_ID")
private long txn_id; public long getTxnId(){return txn_id;} public void setTxnId(long t){this.txn_id=t;}

@Id
@Column(name="BA_SEQ")
private int seq; public int getSeq(){return seq;} public void setSeq(int s){this.seq=s;}



And here are some log statements to show what exactly happens to fail:

In createKeepTxnId of DAO base class: about to commit Transaction :: txn_id->90625 
seq->0 ...<Snip>...

Hibernate: insert into TBL (BA_ACCT_TXN_ID, BA_AUTH_SRVC_TXN_ID, BILL_SRVC_ID, 
BA_BILL_SRVC_TXN_ID, BA_CAUSE_TXN_ID, BA_CHANNEL, CUSTOMER_ID, BA_MERCHANT_FREETEXT, 
MERCHANT_ID, MERCHANT_PARENT_ID, MERCHANT_ROOT_ID, BA_MERCHANT_TXN_ID, BA_PRICE, 
BA_PRICE_CRNCY, BA_PROP_REQS, BA_PROP_VALS, BA_REFERENCE, RESERVED_1, RESERVED_2,
RESERVED_3, SRVC_PROD_ID, BA_STATUS, BA_TAX_NAME, BA_TAX_RATE, BA_TIMESTAMP, BA_SEQ) 
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
[WARN] util.JDBCExceptionReporter SQL Error: 1400, SQLState: 23000
[ERROR] util.JDBCExceptionReporter ORA-01400: cannot insert NULL into 
("SCHEMA"."TBL"."TXN_ID")

The important thing to note is I print out the entity object which has a txn_id set, and then the following insert into statement does not include TXN_ID in the listing and thus the NOT NULL table constraint rejects the query.


Solution

  • how to make a composite primary key (java persistence annotation)

    This helped.

    @IdClass(TxnPK.class)
    

    and then defining a Serializable implementing class TxnPK with fields just like I wanted in my Entity class, as well as equals and hashCode methods.

    annotation on "secondary" fields of the primary key. So @Id on the BA_SEQ field. Also implemented hashCode and equals to supplement.