zmanc
zmanc

Reputation: 5409

How to change JPA / hibernate to delete based on ID instead of object

Below is the JPA setup I am using. I am able to delete objects as expected, however I need to provide an entire object. While I do not mind doing this I do not feel that it is best practice. Is there a way, similar to the findByProductId(int productsId) function that I can use for deleting product that is a native part of JPA?

DAO

 void delete(Products productToDelete);

DAOimpl

@Transactional
public void  delete(Products productToDelete){
    productsManager.delete(productToDelete);
}

Manager

@Resource
@Transactional(readOnly = true)
public interface ProductsManager extends JpaRepository<Products,Integer> {
    Products findByProductId(int productsId);
    List findAll();
}

Here is the test

@Test
public void delete() throws Exception{
    Products productToCreate = new Products();
    productToCreate.setProductName("Test Product");
    productsDao.createProduct(productToCreate);
    List loaded = productsDao.findAll();
    System.out.println("Product: " + loaded);
    assertNotNull(loaded);
    productsDao.delete(productsDao.getProductsById(1));
    List loadedTwo = productsDao.findAll();
    System.out.println("Product After Del: " + loadedTwo);
    assertEquals(loadedTwo.size(),0);
}

Upvotes: 1

Views: 625

Answers (1)

zagyi
zagyi

Reputation: 17518

As I see, your ProductsManager extends JpaRepository (I guess the one from Spring Data JPA), so it inherits a delete method receiving an id (declared in CrudRepository):

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
    ...
    void delete(ID id);
    ...
}

Just expose that method in your DAO interface.

Upvotes: 3

Related Questions