Skip to content

Commit

Permalink
Implement equals and hashCode for Criteria.
Browse files Browse the repository at this point in the history
This facilitates testing of Criteria construction and is also usful, when keeping Criteria instances in sets or similar.

Closes #1960
  • Loading branch information
schauder committed Dec 16, 2024
1 parent e4ba477 commit 721a7ad
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

import org.springframework.dao.InvalidDataAccessApiUsageException;
Expand Down Expand Up @@ -390,6 +391,28 @@ public String toString() {
return builder.toString();
}

@Override
public boolean equals(Object o) {

if (o == null || getClass() != o.getClass()) {
return false;
}

Criteria criteria = (Criteria) o;
return ignoreCase == criteria.ignoreCase //
&& Objects.equals(previous, criteria.previous) //
&& combinator == criteria.combinator //
&& Objects.equals(group, criteria.group) //
&& Objects.equals(column, criteria.column) //
&& comparator == criteria.comparator //
&& Objects.equals(value, criteria.value);
}

@Override
public int hashCode() {
return Objects.hash(previous, combinator, group, column, comparator, value, ignoreCase);
}

private void unroll(CriteriaDefinition criteria, StringBuilder stringBuilder) {

CriteriaDefinition current = criteria;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import java.util.Arrays;

import org.junit.jupiter.api.Test;

import org.springframework.data.relational.core.sql.SqlIdentifier;

/**
Expand Down Expand Up @@ -297,4 +296,31 @@ void shouldBuildIsFalseCriteria() {
assertThat(criteria.getComparator()).isEqualTo(CriteriaDefinition.Comparator.IS_FALSE);
assertThat(criteria.getValue()).isEqualTo(false);
}

@Test // GH-1960
void identicallyCreatedCriteriaAreEqual() {

Criteria c1 = Criteria.where("status").in("PUBLISHED", "DRAFT");
Criteria c2 = Criteria.where("status").in("PUBLISHED", "DRAFT");

assertThat(c1).isEqualTo(c2);
assertThat(c1.hashCode()).isEqualTo(c2.hashCode());
}

@Test // GH-1960
void notIdenticallyCreatedCriteriaAreNotEqual() {

Criteria[] criteria = new Criteria[] { Criteria.where("status").is("PUBLISHED"), //
Criteria.where("statusx").is("PUBLISHED"), //
Criteria.where("status").greaterThan("PUBLISHED"), //
Criteria.where("status").is("PUBLISHEDx") };

for (int i = 0; i < criteria.length - 1; i++) {
for (int j = i + 1; j < criteria.length; j++) {

assertThat(criteria[i]).isNotEqualTo(criteria[j]);
assertThat(criteria[i].hashCode()).isNotEqualTo(criteria[j].hashCode());
}
}
}
}

0 comments on commit 721a7ad

Please sign in to comment.