Reputation: 2550
I want to know whetheris it a GOOD practise to use Objects as composite keys in JPA. For example I have few composite keys and the are foreign keys from another tables and mapped with them.
Composite Class
@Embeddable
public class CashInstrumentComposite implements Serializable {
private static final long serialVersionUID = -6065538857637001219L;
@Column(name = "instrument_id", nullable = false)
private String instrumentId;
@OneToOne
@JoinColumn(name = "company_id")
private Company companyId;
@Column(name = "instrument_type", nullable = true)
@Enumerated(EnumType.STRING)
private InstrumentType instrumentType;
@Column(name = "batch_no", nullable = false)
private String batchNumber;
}
Entity Class
@Entity
@Table(name = "bank_corporate_cash_instrument")
public class CashInstrument extends Model {
/* serial version id. */
private static final long serialVersionUID = 8360452197690274885L;
/* specify the composite key */
@EmbeddedId
private CashInstrumentComposite compositeId;
I can persist using this without any problem, BUT I read this,
http://docs.oracle.com/javaee/6/tutorial/doc/bnbqa.html#bnbqf
It says there that primarykey should be one of
So what did I do wrong here? Please explain.Thank You
Upvotes: 1
Views: 2021
Reputation: 2550
Ok, I did some sample apps I looks like I can use objects as composite keys. But I'm still confuse about whats written in this documentation
http://docs.oracle.com/javaee/6/tutorial/doc/bnbqa.html#bnbqf
But it's not a good practice to use composite keys because when u use one of the key in the composite key as a foreign key, then you have to duplicate the rest of the keys in that composite also. This is a waste specially if you have 4-5 keys as a composite.
Upvotes: 0
Reputation: 19445
I think that you have not interpreted what that piece of documentation says correctly:
The primary key, or the property or field of a composite primary key, must be one of the following Java language types:
Upvotes: 1
Reputation: 3533
@EmbeddedId from javadoc
Is applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable. Example:
@EmbeddedId
protected EmployeePK empPK;
And the EmployeeKey:
@Embeddable
public class EmployeePK {
private Long key1;
private Long key2;
}
You can have a look at:
Upvotes: 0