There are several ways to create an ORM mapped to a composite key using hibernate annotations.
A code sample that shows how to create a composite key with hibernate annotations can be find below:The Composite Key class:
-------------------------
import javax.persistence.Embeddable;
@Embeddable
public class MyCompositeKey implements Serializable {
private static final long serialVersionUID = 8057719523073696665L;
private String name;
private String value;
public MyCompositeKey() {
}
public MyCompositeKey(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name== null) ? 0 : name.hashCode());
result = prime * result + ((value== null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyCompositeKey other = (MyCompositeKey)obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
-------------------------------------------------
The ORM class with the composite key mappings:
-------------------------------------------------
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "my_table_name")
public class MyClassOrm {
private MyCompositeKey id;
private String data;
public MyClassOrm() {
}
@Id
@AttributeOverrides( {
@AttributeOverride(name = "name", column = @Column(name = "name")),
@AttributeOverride(name = "value", column = @Column(name = "value")) })
public MyCompositeKey getId() {
return id;
}
public void setId(MyCompositeKey id) {
this.id = id;
}
@Column(name = "data")
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
No comments:
Post a Comment