One can assign a primary key for its class by using @Id annotation in JPA. My question is what if one doesn't want to have an auto generated key in his tables and use fields (maybe more than one) as a primary key.
Let's say we have a person table with SSN, NATIONALITY and NAME. SSN is defined as the number a person is identified by in his country. Thus, we might have two persons with the same number in two different countries. The primary key for this table can be SSN+NATIONALITY. Is there any way to map these two fields using JPA and map it to an object? or the only way it to create an auto generated id and use @Id annotation
CREATE TABLE PERSON (
SSN INT,
NATIONALITY VARCHAR,
NAME VARCHAR
)
2. Composite Primary Keys. A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.
So yes, you can have more than one @Id. Or is it @EmbeddedId? I can't remember if @EmbeddedId is currently there, or if it is still in discussion by the JSR group for the next version of JPA. JPA 1.0 currently supports two different approaches for compound PKs.
You can have multiple one-to-many associations, as long as only one is EAGER. But, even if you can use Set instead of List to bypass this MultipleBagFetchException , it's not a good thing to do because you'll end up with a Cartesian Product.
Yes, it is possible. A composite primary key consist of multiple primary key fields. Each primary key field must be one of the supported by JPA type. For your table, you have:
@Entity @IdClass(PersonId.class)
public class Person {
@Id int ssn;
@Id String nationality;
....
}
For entity with multiple key, JPA requires defining a special ID class. This class should be attached to the entity class using the @IdClass annotation.
class PersonId {
int ssn;
String nationality;
}
The ID class reflects the primary key fields and its objects can represent primary key values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With