Scene:
The price data type in the database is Decimal, and the price data type in entity class A is BigDecimal. When it is necessary to use equals method to compare the A1 object passed from the front end with the A2 object quashed from the database, the result is false even if the object attributes are the same.
why
Debug found that the price value of the object A1 passed from the front end was 0.1 after JSON transformation, while the price value of the a2 object query from the database was 0.1000. Alt + INSERT equals method was used to call the EQUALS method of BigDecimal.
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");
System.out.println(a.compareTo(b) == 0 ); // true
System.out.println(a.equals(b)); // false
The equals method of BigDecimal compares precision and values, while the compareTo method only compares values.
The solution
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProProductSkuEntity that = (ProProductSkuEntity) o;
return Objects.equals(id, that.id) &&
Objects.equals(productId, that.productId) &&
compareBigDecimal(price, that.price);
}
public boolean compareBigDecimal(BigDecimal a, BigDecimal b) {
return (a == b) || (a != null && a.compareTo(b) == 0);
}
Modify the equals method overwritten in the entity class, customize the compareBigDecimal method, use compareTo to compare values of the BigDecimal type, and you can also put this method in the utility class.
Read More:
- The differences between the equals method in the string class and the equals method in the object class
- Java compareto() method
- Java gets the type t.class of generic t
- Override the equals method and override the toString method
- Compare whether two sets are the same in Java
- Why do we not need to write implementation classes in mybatis to get the objects we need
- Springboot integration redis reports non null key required (solved)
- How to Fix char cannot be dereferenced Error
- SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
- Encapsulation of adding, deleting and modifying database by JDBC
- Java.lang.Character . isdigit() and isletter() methods
- Struts 2 encapsulates form data into list and map sets
- The difference between sleep() and wait() in Java
- Three ways to get form data in struct2
- Android can’t transfer value when using extras, bundle and intent
- How to call stored procedure in Hibernate
- Brief introduction of idea Lombok and solutions for reporting red and wrong
- Common errors and modification methods of findbug
- IOS reverse error: use of undeclared identifier ‘mshookivar’
- 21. Merge Two Sorted Lists [easy] (Python)