Saturday, February 14, 2009

JPA Entities with composite keys

EJB3 spec has made a real come back with JPA. Very often when we need to create a POJO with a composite primary key. JPA makes this very simple. If you want to create an Employee POJO with a composite primary key as first name and last name this is how you do it.

@IDClass(EmployeePK.class)
@Entity(name="EMPLOYEE")
public class Employee implements Serializable{

@ID
private String firstName;
@ID
private String lastName;
private String qualification;
private String speciality;

// getters and setters go here

}



Now create a class called EmployeePK in the same package as Employee class with attributes firstName and lastName.

public class EmployeePK implements Serializable{
private String firstName;
private String lastName;

// getters and setters for firstName and lastName go here...

}

No comments: