TopLink JPA: How to Create, Modify and Delete an Entity

Version: 7/11/06

Introduction

In the Java Persistence API (JPA), a persistent class is referred to as an entity. A JPA entity class possesses the following characteristics:

This How-To document demonstrates the basic operations required to insert an entity, update the data in an entity, and delete an entity.

Persisting a New Entity

You use the EntityManager method persist(Object entity) to mark a new instance of an entity class as "managed" as the following example shows. This adds the instance to the persistence context and marks it for insertion into the database.

entityManager.getTransaction().begin();
Employee newEmployee = new Employee(5);
entityManager.persist(newEmployee);
entityManager.getTransaction().commit();

Once the current transaction is completed, the data within newEmployee will be inserted into the database. The identity of the newEmployee can be assigned automatically by the EntityManager (see Primary Key Generation) or provided in the object by the user (as the previous example shows). If you wish to update the newEmployee in the same transaction, then make those changes directly on the newEmployee instance.

Modifying an Existing Entity

Modifying an entity is as simple as reading that entity within a transaction and changing the properties of that entity as the following example shows. In this example, autoboxing ensures that the literal is passed as an Integer.

entityManager.getTransaction().begin();
Employee existingEmployee = entityManager.find(Employee.class, 5);
existingEmployee.setLastName("NewLastName");
entityManager.getTransaction().commit();

In a container managed persistence context, the transaction boundaries will be controlled by the container.

Deleting an Entity

Deleting an entity is as simple as calling EntityManager method remove(Object entity) as the following example shows. The entity you delete must be managed: that is, it must have been previously read in the current persistence context. In this example, autoboxing ensures that the literal is passed as an Integer.

entityManager.getTransaction().begin();
Employee existingEmployee = entityManager.find(Employee.class, 5);
entityManager.remove(existingEmployee);
entityManager.getTransaction().commit();

When the transaction is completed, or you call EntityManager method flush(), the entity will be deleted.

In a container managed persistence context the transaction boundaries will be controlled by the container.

Summary

This how-to document demonstrated the basics of creating, modifying and deleting a JPA entity.