📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
- Explicit Remove
- Cascading Remove
- Orphan Removal
- DELETE Queries
1. Explicit Remove
private static void removeEntity() {
EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
entityManager.getTransaction().begin();
Student student = entityManager.find(Student.class, 1);
System.out.println("student id :: " + student.getId());
System.out.println("student firstname :: " + student.getFirstName());
System.out.println("student lastname :: " + student.getLastName());
System.out.println("student email :: " + student.getEmail());
entityManager.remove(student);
entityManager.getTransaction().commit();
entityManager.close();
}
2. Cascading Remove
Instructor.java
@Entity
@Table(name="instructor")
public class Instructor {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="instructor_detail_id")
private InstructorDetail instructorDetail;
@OneToMany(mappedBy="instructor",
cascade= {CascadeType.REMOVE})
private List<Course> courses;
// getters and setters
}
Course.java
@Entity
@Table(name="course")
public class Course {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="title")
private String title;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="instructor_id")
private Instructor instructor;
// getters and setters methods
}
3. Orphan Removal
@Entity
class Employee {
:
@OneToOne(orphanRemoval=true)
private Address address;
:
}
@Entity
class Employee {
:
@OneToMany(orphanRemoval=true)
private List<Address> addresses;
:
}
4. DELETE Queries
Delete All Queries
DELETE FROM Country // no variable
DELETE FROM Country c // an optional variable
DELETE FROM Country AS c // AS + an optional variable
int deletedCount = em.createQuery("DELETE FROM Country").executeUpdate();
Refer complete JPA CRUD operations example at JPA CRUD Example
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
Comments
Post a Comment
Leave Comment