请考虑以下示例:
import org.hibernate.annotations.NaturalId;
import javax.persistence.Column;
import javax.persistence.Table;
@javax.persistence.Entity
@Table(name = "Entity", uniqueConstraints = {
@javax.persistence.UniqueConstraint(columnNames = {"firstNaturalId"}),
@javax.persistence.UniqueConstraint(columnNames = {"secondNaturalIdPart1", "secondNaturalIdPart2"})
})
class Entity {
@NaturalId
@Column(name = "firstNaturalId")
private String firstNaturalId;
@NaturalId
@Column(name = "secondNaturalIdPart1")
private String secondNaturalIdPart1;
@NaturalId
@Column(name = "secondNaturalIdPart2")
private String secondNaturalIdPart2;
// The remainder is omitted.
}
所需的功能是能够通过提供('firstNaturalId'
)或('secondNaturalIdPart1', 'secondNaturalIdPart2'
)组来检索已识别的唯一实体。
Hibernate中是否可以有多个自然标识符组合(组)来唯一标识表中的实体?
答案 0 :(得分:0)
好久不见。或许你已经有了答案。我心里有这个疑问。发现你的问题没有答案。搜索了更多。找到了这个 Natural Id Mapping。
public class Entity{
@NaturalId @Embedded
private EntityNI entityNI;
public Entity(){}
// Setter and Getter is omitted
// .
// .
// .
@Override
public int hashCode(){
return (entityNI != null ? entityNI.hashCode() : 31);
}
@Override
public boolean equals(final Object object){
if(this == object){
return true;
}
if( !(object instanceof Entity) || (getClass() != object.getClass()) ){
return false;
}
return this.entityNI.equals( ((Entity)object).entityNI );
}
}
以及嵌入的自然 ID:
@Embeddable
public class EntityNI{
@NotBlank @Basic(optional = false) @Column(name = "firstNaturalId")
private String firstNaturalId;
@NotBlank @Basic(optional = false) @Column(name = "secondNaturalIdPart1")
private String secondNaturalIdPart1;
@NotBlank @Basic(optional = false) @Column(name = "secondNaturalIdPart2")
private String secondNaturalIdPart2;
public EntityNI(){}
// Setters and Getters are omitted
// .
// .
// .
@Override
public int hashCode(){
return Objects.hash(firstNaturalId, secondNaturalIdPart1, secondNaturalIdPart2);
}
@Override
public boolean equals(Object object){
if(this == object){
return true;
}
if( !(object instanceof EntityNI) || (getClass() != object.getClass()) ){
return false;
}
final EntityNI other = (EntityNI) object;
return (this.firstNaturalId == other.firstNaturalId) && (this.secondNaturalIdPart1 == other.secondNaturalIdPart1) && (this.secondNaturalIdPart2 == other.secondNaturalIdPart2);
}
}