The Java Persistence API is a specification for:
- accessing
- persisting
- and managing
data between Java objects / classes and a relational database
JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry.
JPA itself is just a specification, not a product. It cannot perform persistence or anything else by itself. JPA is just a set of interfaces and requires an implementation
A provider is needed. There are several:
- Hibernate
- EclipseLink
- OpenJPA
Hibernate is used in more than 70% of projects
assuming you already have your database set up...
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence ... version="2.1">
<persistence-unit name="h2" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:testdb"/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto"
value="update"/>
</properties>
</persistence-unit>
</persistence>
public class Author {
private String firstName;
private String lastName;
// Constructors, getters and setters..
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public Author() {
}
// Constructors, getters and setters..
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("h2");
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
Author author = new Author("Tom", "Clancy");
transaction.begin();
manager.persist(author);
transaction.commit();
Long authorId = 1L;
Author author = manager.find(Author.class, authorId);
but something's wrong...
author can be null!
transaction.begin();
Author author = new Author("Tom", "Clancy");
manager.persist(author);
Author authorToBeFound = new Author();
authorToBeFound.setId(1L);
authorToBeFound.setFirstName("Arnold");
authorToBeFound.setLastName("Schwarzenegger");
transaction.begin();
Author found = manager.merge(authorToBeFound);
transaction.commit();
Hibernate:
insert into Author (id, first_name, last_name)
values (null, ?, ?)
Author{id=1, firstName='Tom', lastName='Clancy'}
Hibernate:
update Author
set
first_name=?,
last_name=?
where id=?
Author{id=1, firstName='Arnold', lastName='Schwarzenegger'}
Long authorId = 1L;
author = manager.find(Author.class, authorId);
transaction.begin();
author.setId(1L);
author.setFirstName("Arnold");
author.setLastName("Schwarzenegger");
transaction.commit();
Optional.ofNullable(manager.find(Author.class, authorId))
.ifPresent(found -> {
transaction.begin();
manager.remove(found);
transaction.commit();
});
Author toBeRemoved = new Author();
toBeRemoved.setId(1L);
transaction.begin();
manager.remove(manager.merge(toBeRemoved);
transaction.commit();