How to Delete JPA in Java

How to Delete JPA in Java thumbnail
JPA is a major component of Java Enterprise Edition 5 (Java EE5).

The Java Persistence API, or JPA, is a major component of the Java Enterprise Edition 5 (Java EE 5) EJB 3.0 specification, which controls Java persistence and simplifies its effect in a Java Standard Edition 5 (Java SE 5) application. It also allows you to define a method by which you will map your Java objects to relational database tables and gives you the freedom to add, update and delete JPA objects in your project.

Instructions

    • 1

      Paste the following code to delete a JPA object from the database. This is the "remove" method:

      Employee employee = em.find(Employee.class, 1);

      em.getTransaction().begin();

      em.remove(employee);

      em.getTransaction().commit();

      This is just one of the ways to delete a JPA object from your database. When you commit this transaction, it physically deletes the entity object from your database. But should you decide to keep the data, all you have to do is cancel the transaction, or not post it, to keep the data intact. This concept is also referred to as the "explicit remove" method.

    • 2

      Paste the code below to mark a reference field with CascadeType.REMOVE, or CascadeType.ALL, which includes REMOVE, whichever you prefer, of an entity or entities you wish to remove:

      @Entity

      class Employee {

      :

      @OneToOne(cascade=CascadeType.REMOVE)

      private Address address;

      :

      }

      Because of the cascading effect of the CascadeType.REMOVE method, every "Address" instance of the "Employee" class in the database will be deleted after you tag the address field that references to that specific instance.

    • 3

      Paste the succeeding code to activate a more aggressive "remove cascading" mode that uses the orphanRemoval component of the @OneToOne and @OneToMany annotations:

      @Entity

      class Employee {

      :

      @OneToOne(orphanRemoval=true)

      private Address address;

      :

      }

      In this example, orphanRemoval=true and cascade=CascadeType.REMOVE are similar, which makes the CascadeType.REMOVE a redundant method, therefore it will not delete anything; only the orphanRemoval function will perform the deletion because it is set to "true" status.

Tips & Warnings

  • Learn the acronyms for the Java language program to better understand the tutorials you will find online.

  • Join discussion forums to seek expert advice from renowned Java programmers.

Related Searches:

References

Resources

  • Photo Credit Stockbyte/Stockbyte/Getty Images

Comments

Related Ads

Featured