DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. 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 · Tutorial
Like (5)
Save
Tweet
Share
4.86K 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

  • Using JSON Web Encryption (JWE)
  • Easy Smart Contract Debugging With Truffle’s Console.log
  • Kubernetes vs Docker: Differences Explained
  • Beginners’ Guide to Run a Linux Server Securely

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: