JPA delete data
In this section we will show you how to delete the persistent unit using JPA api.JPA provide remove(Object) to remove the object from the persistence store. To remove the object, we need to first find the object and then remove the object using remover(Object) method of JPA api.
Follow the following steps to create and run the example code:
Create a "JPADelete.java" file.
Put the following text in "JPADelete.java"
file.
Delete code:
/** * */ package roseindia; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; /** * @author Administrator * */ public class JPADelete { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa"); EntityManager em = emf.createEntityManager(); try{ em.getTransaction().begin(); //find Student stud1 = em.find(Student.class,1); //delete em.remove(stud1); em.getTransaction().commit(); } catch(Exception e){ System.out.println(e.getMessage()); } finally{ em.close(); } } } |
Run it and get the output in "Console
window" of eclipse.
Check it in MySQL.