Colegas,
No for abaixo quero comparar a igualdade entre os objetos ServicoCategoria, porém não retorna igual.
Obseve que se eu comparo pelos ids retorna igual, porém os objetos ele diz que são diferentes.
Onde estou errando?
public void prepareEditare(ServicoPlano plano) {
String query = "from ServicoCategoria o order by o.categoria, o.descricao";
Map<String, Object> params = new HashMap<String, Object>();
servicoCategorias = servicoCategoriaService.findByParam(query, params);
for (ServicoCategoria servicoCategoria : servicoCategorias) {
if (servicoCategoria.getId().compareTo(plano.getCategoriaServico().getId()) == 0) {
System.out.println("Se os ids são iguais, por que na comparação dos objetos na linha abaixo não são iguais?");
boolean teste = servicoCategoria.equals(servicoPlano.getCategoriaServico());
System.out.println("Valor de teste: " + teste); // teste retorna false
}
}
}
public abstract class Entity implements Serializable {
public abstract Long getId();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Long.signum(getId() ^ (getId() >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (getId() != other.getId())
return false;
return true;
}
}
@javax.persistence.Entity
@Table(name = "servico_categoria")
public class ServicoCategoria extends Entity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(name = "categoria", nullable = false)
@Enumerated(EnumType.STRING)
private ServicoCategoriaEnum categoria;
private String descricao;
public ServicoCategoria() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ServicoCategoriaEnum getCategoria() {
return categoria;
}
public void setCategoria(ServicoCategoriaEnum categoria) {
this.categoria = categoria;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof ServicoCategoria))
return false;
ServicoCategoria other = (ServicoCategoria) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}