title: Create the perfect JPA entity
body: <p>I've been working with JPA (implementation Hibernate) for some time now and each time I need to create entities I find myself struggling with issues as AccessType, immutable properties, equals/hashCode, ... .<br>
  So I decided to try and find out the general best practice for each issue and write this down for personal use.<br>
  I would not mind however for anyone to comment on it or to tell me where I'm wrong.</p>
  
  <h2>Entity Class</h2>
  
  <ul>
  <li><p>implement Serializable  </p>
  
  <p>Reason: <em>The specification says you have to, but some JPA providers do not enforce this. Hibernate as JPA provider does not enforce this, but it can fail somewhere deep in its stomach with ClassCastException, if Serializable has not been implemented.</em></p></li>
  </ul>
  
  <h2>Constructors</h2>
  
  <ul>
  <li><p>create a constructor with all required fields of the entity </p>
  
  <p><em>Reason: A constructor should always leave the instance created in a sane state.</em>  </p></li>
  <li><p>besides this constructor: have a package private default constructor  </p>
  
  <p><em>Reason: Default constructor is required to have Hibernate initialize the entity; private is allowed but package private (or public) visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.</em></p></li>
  </ul>
  
  <h2>Fields/Properties</h2>
  
  <ul>
  <li><p>Use field access in general and property access when needed  </p>
  
  <p><em>Reason:  this is probably the most debatable issue since there are no clear and convincing  arguments for one or the other (property access vs field access); however, field access seems to be general favourite because of clearer code, better encapsulation and no need to create setters for immutable fields</em> </p></li>
  <li><p>Omit setters for immutable fields (not required for access type field)</p></li>
  <li>properties may be private<br>
  Reason: I once heard that protected is better for (Hibernate) performance but all I can find on the web is: <em>Hibernate can access public, private, and protected accessor methods, as well as public, private and protected fields directly. The choice is up to you and you can match it to fit your application design.</em></li>
  </ul>
  
  <h2>Equals/hashCode</h2>
  
  <ul>
  <li>Never use a generated id if this id is only set when persisting the entity</li>
  <li>By preference: use immutable values to form a unique Business Key and use this to test equality</li>
  <li>if a unique Business Key is not available use a non-transient <strong>UUID</strong> which is created when the entity is initialised; See <a href="https://web.archive.org/web/20171211235806/http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" rel="noreferrer">this great article</a> for more information.</li>
  <li><strong>never</strong> refer to related entities (ManyToOne); if this entity (like a parent entity) needs to be part of the Business Key then compare the ID's only. Calling getId() on a proxy will not trigger the loading of the entity, as long as you're using <a href="https://stackoverflow.com/questions/3736818/hibernate-generating-sql-queries-when-accessing-associated-entitys-id/3739197#3739197">property access type</a>.</li>
  </ul>
  
  <h2>Example Entity</h2>
  
  <pre><code>@Entity
  @Table(name = "ROOM")
  public class Room implements Serializable {
  
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue
      @Column(name = "room_id")
      private Integer id;
  
      @Column(name = "number") 
      private String number; //immutable
  
      @Column(name = "capacity")
      private Integer capacity;
  
      @ManyToOne(fetch = FetchType.LAZY, optional = false)
      @JoinColumn(name = "building_id")
      private Building building; //immutable
  
      Room() {
          // default constructor
      }
  
      public Room(Building building, String number) {
          // constructor with required field
          notNull(building, "Method called with null parameter (application)");
          notNull(number, "Method called with null parameter (name)");
  
          this.building = building;
          this.number = number;
      }
  
      @Override
      public boolean equals(final Object otherObj) {
          if ((otherObj == null) || !(otherObj instanceof Room)) {
              return false;
          }
          // a room can be uniquely identified by it's number and the building it belongs to; normally I would use a UUID in any case but this is just to illustrate the usage of getId()
          final Room other = (Room) otherObj;
          return new EqualsBuilder().append(getNumber(), other.getNumber())
                  .append(getBuilding().getId(), other.getBuilding().getId())
                  .isEquals();
          //this assumes that Building.id is annotated with @Access(value = AccessType.PROPERTY) 
      }
  
      public Building getBuilding() {
          return building;
      }
  
  
      public Integer getId() {
          return id;
      }
  
      public String getNumber() {
          return number;
      }
  
      @Override
      public int hashCode() {
          return new HashCodeBuilder().append(getNumber()).append(getBuilding().getId()).toHashCode();
      }
  
      public void setCapacity(Integer capacity) {
          this.capacity = capacity;
      }
  
      //no setters for number, building nor id
  
  }
  </code></pre>
  
  <p>Other suggestions to add to this list are more than welcome...</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Since reading <a href="https://web.archive.org/web/20171211235806/http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" rel="noreferrer">this article</a> I have adapted my way of implementing eq/hC:</p>
  
  <ul>
  <li>if an immutable simple business key is available: use that</li>
  <li>in all other cases: use a uuid</li>
  </ul>