JPA-Java Persistence API Basics

 

What is JPA?

JPA stands for Java Persistence API. It is a Java API specification which describe the management of relational data.

 
What's the need for JPA?
    Object-relational technologies aims at mapping the relational data in database to Object-oriented model in Java. Various object-relational technologies like Hibernate, Toplink, EJB, JDO are in existence. JPA was introduces as part of Java EE 5 platform and it provides a standardized way of dealing with data persistence.
 
JPA implementations?
    As mentioned earlier, JPA is an API and various implementations like Hibernate, OpenJPA, Toplink, batooJPA, EclipseLink JPA.
 
Building Blocks of JPA:
 
Entity:
    Entity is the domain object which is used for persistence. Usually, an entity represents a table. Each instance corresponds 
to a row. In order for a POJO to be an entity class
  • Should be annotated with @Entity
  • Should have default or no arg constructor
  • Should implement Serializable if the entity will be used as a detached object
  • Persistence variables should not be public.
Entity Properties:
  • All properties of entity are considered persistent except static and transient properties
  •  
 
 
 Annotation  Example    
 @Id      
 @Column @Column(updatable = false, name = "flight_name", nullable = false, length=50)    
 @Transient      
 @Basic      
 @Lob      
 @Version          
 @Embedded      
 @Embeddable      
 @EmbeddedId      
 @Inheritance      
 @OneToOne      
 @ManyToOne      
 @OneToMany      
 @ManyToOne      
 @ManyToMany      
 @NamedQuery      
       
 
Querying Entities
    There are two ways for querying entities
  • JPQL - Java Persistence Query Language
  • Criteria API 
persistence.xml
    Similar to hibernate.cfg.xml file in hibernate, JPA used its own configuration file named persistence.xml. The provider is required to locate all JPA config files by classpath lookup of the META-INF/persistence.xml resource name.
 
persistence.xml files should provide a unique name for each persistence unit. This name is how applications reference the configuration while obtaining an javax.persistence.EntityManagerFactory reference. 
 
Web Analytics