Entities Are POJOs




Entities Are POJOs

Entities, in the Java Persistence specification, are plain old Java objects (POJOs). You allocate them with the new( ) operator just as you would any other plain Java object. Instances of an entity bean class do not become persistent until they are associated with an EntityManager. For instance, let's look at a simple example of a Customer entity:

import javax.persistence.*;

@Entity
public class Customer {
   private int id;
   private String name;

   @Id @GeneratedValue
   public int getId( ) {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }

   String getName( ) {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

If we allocate instances of this Customer class, no magic happens when new( ) is invoked. Calling the new operator does not magically interact with some underlying service to create the Customer class in the database:

Customer cust = new Customer( );
cust.setName("Bill");

Allocated instances of the Customer class remain POJOs until you ask the EntityManager to create the entity in the database.