JPA Tutorial - JPA EntityManager Remove Example

We can use EntityManager from JPA to remove an entity.

In the following code we first get a person object from database by using the find method from EntityManager then call the remove method and pass in the person object reference.

    Person emp =  em.find(Person.class, 1L);
    if (emp != null) {


The following code is from

package com.java2s.common;
import static javax.persistence.FetchType.LAZY;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

public class Person {
  @Column(name = "EMP_ID")
  private long id;
  private String name;
  private String surname;
  private byte[] picture;
  public Person() {}

  public Person(String name, String surname) { = name;
    this.surname = surname;
  public Long getId() {
    return id;
  public void setId(Long id) { = id;
  public String getName() {
    return name;
  public void setName(String name) { = name;
  public String getSurname() {
    return surname;
  public void setSurname(String surname) {
    this.surname = surname;
  public byte[] getPicture() {
    return picture;

  public void setPicture(byte[] picture) {
    this.picture = picture;

  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", surname=" + surname + "]";

The following code is from

package com.java2s.common;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

public class PersonDaoImpl {
  public void test(){
    Person p1 = new Person("Tom", "Smith");
    Person p2 = new Person("Jack", "Kook");

    Person emp =  em.find(Person.class, 1L);
    if (emp != null) {
  private void listAll(){
    List<Person> persons = getAll();
    for (Person person : persons) {

  private EntityManager em;
  public Long save(Person person) {
    return person.getId();
  public List<Person>getAll() {
    return em.createQuery("SELECT p FROM Person p", Person.class).getResultList();


The code above generates the following result.

The following is the database dump.

Table Name: EMP
    Column Name: EMP_ID,
    Column Type: BIGINT:
    Column Value: 2

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Jack

    Column Name: PICTURE,
    Column Type: BLOB:
    Column Value: null

    Column Name: SURNAME,
    Column Type: VARCHAR:
    Column Value: Kook

From the database dump we can see that the Person entity with id equals 1 is removed from the database.