Thirumal
Thirumal

Reputation: 9666

How to create JPA class for composite primary key

I have table with composite primary keys

site_Uid --> from Site table
address_Uid --> from Address table

The below JPA class throws an exception

@Entity @IdClass(Site.class)
@Table(name = "site_address")
public class SiteAddress implements Serializable {

    private static final long serialVersionUID = 7237095501517057347L;
    @Id
    @Column(name = "site_uid")
    private int siteUid;
    @Column(name = "address_uid")
    @Id
    private int addressUid;
}

Site Class:

@Entity
@Table(name = "site")
public class Site implements Serializable {

    private static final long serialVersionUID = 2059474818667179203L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long siteUid;
    @Column(name = "party_role_uid")
    private int partyRoleUid;
    @Column(name = "site_type_cd")
    private int siteTypeCd;
    @Column(name = "site_name")
    private String siteName;

}

Error:

Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to find properties (siteTypeCd, siteName, partyRoleUid) in entity annotated with @IdClass:com.enkindle.model.SiteAddress

Upvotes: 1

Views: 4143

Answers (1)

Jonathan Sterling
Jonathan Sterling

Reputation: 604

Make a SiteAddressId class with two fields: int siteUid and int addressUid. Then in SiteAddress do: @IdClass(SiteAddressId.class).

See here for more info: http://www.objectdb.com/java/jpa/entity/id#Composite_Primary_Key_

Upvotes: 3

Related Questions