Delete Operation in Java Persistence with Spring Data and Hibernate
Overview
The delete operation is a fundamental aspect of data management in applications using Java Persistence with Spring Data and Hibernate. It involves removing entities from the database, which can be performed using various frameworks and approaches. This page explores the delete operation, its implementation, and performance considerations.
Implementation of Delete Operation
DAO Pattern
In the Data Access Object (DAO) pattern, the delete operation is implemented to remove entities from the database. For example, in the ItemDaoImpl class, the delete method is responsible for removing all bids associated with an Item and the Item itself. Similarly, in the BidDaoImpl class, the delete method is used to remove a Bid.
Using Hibernate API
The delete operation can be implemented using the Hibernate API, as shown in the following code snippet from the AbstractGenericDao class:
@Override
public void delete(T entity) { #7
sessionFactory.getCurrentSession().delete(entity); #7
}
#7 Remove the entity.
In this implementation, the delete method removes the specified entity from the current session.
Managing Independent Entity Instances
When managing independent entity instances, it is crucial to handle associations correctly. The following listing demonstrates managing independent entity instances separately:
Path: Ch08/mapping-associations/src/test/java/com/manning/javapersistence
/ch08/onetomany/bidirectional/MappingAssociationsSpringDataJPATest.java
Item item = new Item("Foo");
Bid bid = new Bid(BigDecimal.valueOf(100), item);
Bid bid2 = new Bid(BigDecimal.valueOf(200), item);
itemRepository.save(item);
item.addBid(bid);
item.addBid(bid2);
bidRepository.save(bid);
bidRepository.save(bid2);
In this example, an Item and its associated Bids are managed independently, ensuring that each entity is correctly persisted and can be deleted when necessary.
Performance Considerations
The performance of delete operations can vary depending on the framework used. The following figure illustrates the execution times for delete operations across different frameworks:
Figure 2.9 Delete execution times by framework (times in ms)
The performance comparison shows that Hibernate and JPA have similar execution times for delete operations. Despite JPA having an additional API layer on top of Hibernate, it does not introduce significant overhead, resulting in comparable performance for both frameworks.
FAQ (Frequently asked questions)
What does Figure 2.9 in the book show?
How are independent entity instances managed in the book's example?
How is the delete operation implemented in the AbstractGenericDao class?