DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Hibernate Fix: Avoid Referencing the ID in the Persistent Class's Equals()

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.

Michael Muller user avatar by
Michael Muller
·
Nov. 30, 16 · Java Zone · Tutorial
Like (5)
Save
Tweet
4.71K Views

Join the DZone community and get the full member experience.

Join For Free

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
    }
}


Hibernate

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Modify Java Command-Line Arguments
  • How to Build Security for Your SaaS User Communications
  • Which JVM Version Is the Fastest?
  • Streaming ETL with Apache Kafka in the Healthcare Industry

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo