Skip to the content.

JPA

Java Persistence API

-

JPA Specification

-

Hibernate

-

ORM (definition)

-

Spring repositories

-

Repositories

-

Existing repository types

- Method names parsed and automatically implemented

<verb><subject?>By<predicate>()
eg: findCarByYear() or countDistictPersonByLastName()

-

Verbs

-

Subject

-

Predicate

- Repositories provide indirect JPA access – we can still directly access using @persistencecontext/@entitymanager (later)

-

JPA Annotations

- @Entity

- @ID

- @OneToMany, @ManyToOne, @OneToOne, @ManyToMany

Indicate relationships between entities eg:

@Entity
public class Room{
...
@OneToMany
private List<Window> windows;

-

More about Repository methods

- Access Sub-properties in predicates

- Specify custom queries

- Custom query example

@Query("select c from Customer c where c.emailAddress = ?1")
Customer findByEmailAddress(EmailAddress email);

- Custom implementations (example to follow)

- Custom JPA example

interface ClassicCarUpdater {
  int updateClassics();
}

public class CarRepositoryImpl implements ClassicCarUpdater {
  @PersistenceContext
  private EntityManager em;

  public int updateClassics() {
    String update =
      "UPDATE Cars car SET car.isClassic = true " +
      "WHERE car.isClassic = false " +
      "AND car.id IN (" +
      "SELECT c from Cars c WHERE c.year < 1992)";
    return em.createQuery(update).executeUpdate();
  }
}

- Custom JPA example (repository)

public interface CarRepository extends
        JPARepository<Car, Integer>,
        ClassicCarUpdater {
    ...
    }

-

Configuration hints:

- @PersistenceContext and @PersistenceUnit