Tuesday, January 10, 2006

Using @IdClass in Glassfish

Given below is an example of how to use @IdClass in Glassfish. Note that the primary key class must not have any members other than the Id fields, not even serialVersionUID, even though the primary key class is defined as Serializable.

@Entity
@Table(name = "WAREHOUSE", schema = "TPCC")
@IdClass(entity.tpcc.WarehousePK.class)
public class Warehouse {

String name;
String city;

@Id
@Column(name = "W_NAME", length = 10)
public String getName() {
return name;
}

@Id
@Column(name = "W_CITY", length = 20)
public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public void setName(String name) {
this.name = name;
}
}

public class WarehousePK implements Serializable {

String name = "";
String city = "";

public WarehousePK() {
}

public String getCity() {
return city;
}

public String getName() {
return name;
}

public void setCity(String city) {
this.city = city;
}

public void setName(String name) {
this.name = name;
}

@Override
public boolean equals(Object arg0) {
if (arg0 == this) {
return true;
}
else if (arg0 instanceof WarehousePK) {
return name.equals(((WarehousePK)arg0).name) &&
city.equals(((WarehousePK)arg0).city);
}
return false;
}

@Override
public int hashCode() {
return name.hashCode() ^ city.hashCode();
}
}
The primary key class is useful when searching for objects by their primary key. Example:

    WarehousePK key = new WarehousePK();
key.setName("LONDON WAREHOUSE");
key.setCity("LONDON");
Warehouse w = em.find(Warehouse.class, key);
When creating new entities of updating existing entities, you should access the properties within the entity as normal. Example:

    Warehouse w = new Warehouse();
w.setName("LONDON WAREHOUSE");
w.setCity("LONDON");

1 comment:

vartika said...

This site helped us a lot. We were stuck on implementing composite key through JPA from very long. Thank you for providing with a good example.