Transient properties

We take a closer look at Figure 925, “Mapping hibintro.v1.model.User instances to a database. ” assuming that Instances of hibintro.v1.model.User need an additional GUI related property selected ❶:

package hibintro.v2;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * A simple class intended to be mapped to a database server
 */
@Entity
public class User {

  String uid;
  /**
   * @return  The user's unique login name e.g. "goik"
   */
  @Id
  public String getUid() {
    return uid;
  }
  /**
   * @param uid See {@link #getUid()}.
   */
  public void setUid(String uid) {
    this.uid = uid;
  }
  String cname;
  /**
   * @return The user's common name e.g. "Martin Goik"
   */
  public String getCname() {
    return cname;
  }
  /**
   * @param cname See {@link #getCname()}.
   */
  public void setCname(String cname) {
    this.cname = cname;
  }

  boolean selected = false; ❶
  
  public boolean isSelected() {
   return selected;
  }
  public void setSelected(boolean selected) {
     this.selected = selected;
  }
  protected User() {}

  /**
   * @param uid See {@link #getUid()}.
   * @param cname See {@link #getCname()}.
   */
  public User(String uid, String cname) {
    this.uid = uid;
    this.cname = cname;
  }
}

Hibernates produces the following DDL statements containing an attribute selected ❶:

CREATE TABLE User (
  uid VARCHAR(255) NOT NULL PRIMARY KEY,
  cname VARCHAR(255),
  selected ❶ BIT NOT NULL,
) 

If we just annotate a Java class with an javax.persistence.Entity Annotation all properties of the class in question will be mapped. A JPA framework of course cannot distinguish between transient and persistent properties. If we want a property to be transient we have to add a javax.persistence.Transient annotation:

Java
package hibintro.v3;

@Entity
public class User {
       ...
  boolean selected = false;
  @Transient ❶
  public boolean isSelected() { return selected; }
  public void setSelected(boolean selected) { this.selected = selected; }
       ...
}
SQL
CREATE TABLE User ( 
    uid VARCHAR(255) NOT NULL PRIMARY KEY,
    cname VARCHAR(255)
) 

The javax.persistence.Transient annotation inhibits the mapping of our property selected.

Caution

When loading a hibintro.v3.User instance from a database all transient property values are of course entirely determined by the default constructor.