Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Hibernate Fix: Avoid Referencing the ID in the Persistent Class's Equals()

DZone's Guide to

Hibernate Fix: Avoid Referencing the ID in the Persistent Class's Equals()

See how to use business keys for your equals() and HashCode() methods to create better, more secure code.

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Because the programmer can define the meaning of Java Equality, it is important not to use the id field in this definition if the id field is a surrogate key. This is because Hibernate only sets the field when saving the object. Hence, for example, if you add the object to some set collection, then saving the object will result in its identity changing, and part of the rules about using Set/Map collection class is that the contained object's identity must not change while it is in the collection (the behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element).

How Industries and Developers Comply With This Quality Tule

A benchmark of this coding rule across 9k opportunities in CAST Appmarq's code base (more than 2,000 applications are analyzed, monitored, and benchmarked) tells us developers comply in 6 cases out of 10, with 20 violations by application on average. This global compliance score (60.88%) is pretty low if we consider critical security rules generally score around 95% across the different programming languages and industries.

This good Hibernate practice scores even worse for Insurers. When development teams from Financial Services receive a compliance score of 78%, Insurance organizations miss the point almost half the time (58.24%). Don't hesitate to download our last series of CRASH reports dedicated to FiServ and Insurance to discover other kinds of quality issues they currently face.

Image title

How to Fix This Defect

Implement your equals() and hashCode() methods based on business keys. In cases where the business key is composite, you can use the Jakarta Commons libraries — in particular, the EqualsBuilder and HashCodeBuilder classes. It may be that your class is not an @Entity, but a value object (@Embeddable) instead and perhaps the entity needs to be modelled in a different way.

Violation Code Sample

------> sample.hbm.xml:
...
<class name="Sample" table="SAMPLE">
           <id name="id" column="id" type="long">
                  <generator class="sequence"/>
           </id>
           <property name="name" column="NAME" type="string"/>
...
</class>

------> Sample.java:
publicclass Sample {
   privatelong id;
   private String name;
...
   public String getName(){
      return name;
   }

   public Long getId(){
      return id;
   }

    public boolean equals(Object other){
        if (this==other) returntrue;
        if ( !(other instanceof Sample) ) returnfalse;
        final Sample that = (Sample) other;
        returnthis.getId().equals( that.getId()); // VIOLATION
    }
}


Fixed Code Sample

------> Sample.java:
publicclassSample{
   privatelong id;
   private String name;
   ...
   public String getName(){
      return name;
   }

   public Long getId(){
      return id;
   }

    publicbooleanequals(Object other){
        if (this==other) returntrue;
        if ( !(other instanceof Sample) ) returnfalse;
        final Sample that = (Sample) other;
        returnthis.getName().equals( that.getName()); // FIXED
    }
}


Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
hibernate ,benchmark ,java ,software quality

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}