What is JPA?

  • JPA stands for Java Persistence API
  • Official API for working with relational data in Java
  • Only a specification
    • JPA is not a concrete implementation (Other vendors, different implementation)
      • Hibernate, Eclipse Link, OpenJpa

What does JPA do?

  • JPA is a bridge from Java’s object world to how data is stored in relational databases (ORM - Object Relational Mapping)
  • JPA offers Java developers database independence
  • One API will support many relational databases

Some Databases Supported by Hibernate:

  • Oracle 11g • DB2 9.7
  • MySQL 5.1, 5.5
  • PostgreSQL 8.4, 9.1

How to use JPA:

  • Normal Todo Java Class
public class Todo {

    private final String name;

    private final String description;

    private final Long createdAt;

    public Todo(String name, String description, Long createdAt) {
        this.name = name;
        this.description = description;
        this.createdAt = createdAt;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public Long getCreatedAt() {
        return createdAt;
    }

}
  • JPA Todo Java Class
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Todo {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private String description;

    private Long createdAt;

    //Required by JPA (https://stackoverflow.com/questions/18099127/java-entity-why-do-i-need-an-empty-constructor)
    public Todo() {
    }

    public Todo(String name, String description, Long createdAt) {
        this.name = name;
        this.description = description;
        this.createdAt = createdAt;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public Long getCreatedAt() {
        return createdAt;
    }

}

To use use a UUID instead of Long when storing the id, use:

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    private String id;

results matching ""

    No results matching ""