| Lesson 3 | Creating Entities with JPA |
| Objective | Learn how to create and persist entities in JPA, and retrieve them by primary key. |
In JPA, creating an entity instance is straightforward. Instead of EJB-specific lifecycle methods like
ejbCreate(), you define a plain Java class annotated with @Entity and use
EntityManager.persist() to save it to the database.
Suppose you have a Customer entity with a primary key of type Long. You create
a new instance, set its fields, and call persist() inside a transaction.
@Entity
public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters, setters, constructors
}
@Transactional
public void createCustomer(String name) {
Customer customer = new Customer();
customer.setName(name);
em.persist(customer);
// customer.id is generated after flush/commit
}
The persistence provider automatically inserts the row into the database and manages the primary key generation.
In modern JPA, you retrieve an entity using EntityManager.find():
Customer customer = em.find(Customer.class, 123L);
if (customer != null) {
// Found
} else {
// Not found
}
This replaces legacy ejbFindByPrimaryKey() methods and avoids manual JDBC code for lookups.
JPA offers lifecycle callbacks like @PrePersist and @PostPersist to perform logic
before and after saving an entity. These replace ejbPostCreate() in legacy EJB code.
@PrePersist
public void beforeInsert() {
System.out.println("About to insert customer: " + name);
}