I have some objects I cannot delete, and must update a common field named 'deleted' instead of it. I read there that I can write generic querys, using #{#entityName}
.
For that reason I tried to override CrudRepository#delete(…)
method like this:
public interface DeleteableRepository<T, ID extends Serializable> extends CrudRepository<T,ID>{
@Override
@Query("UPDATE #{#entityName} x set x.deleted = 1 where x.id = ?1")
public void delete(ID id);
}
But the I have a unit test that shows me wrong!
@Test
public void testDelete() {
SomeDeleteableObject sdo = new SomeDeletableObject();
sdo = getDeleteableRepository().create(sdo);
Assert.assertNotNull(sdo);
Assert.assertNotNull(sdo.getId());
Assert.assertFalse(sdo.isDeleted());
getDeleteableRepository().delete(sdo);
sdo = getDeleteableRepository().findOne(sdo.getId());
//Fails here
}
Isn't it possible to override CrudRepository
methods like that?
CrudRepository is a Spring data interface and to use it we need to create our interface by extending CrudRepository for a specific type. Spring provides CrudRepository implementation class automatically at runtime. It contains methods such as save, findById, delete, count etc. If we want to add extra methods, we need to declare it in our interface.
As the name depicts, the delete () method allows us to delete an entity from the database table. It belongs to the CrudRepository interface defined by Spring Data. Let's first create a Product entity that we are going to use to save and delete to/from the database: Let's create ProductRepository which extends the CrudRepository interface.
Delete from Repository Among others, CrudRepository contains two methods: deleteById and deleteAll. Let's test these methods directly from our BookRepository:
In order to test the deleteById () method, we gonna use CommandLineRunner.run () method to execute the testing code while Spring boot application startup: After finishing the Spring boot application, you can able to see Hibernate-generated SQL statements in a console.
For modifying queries you need to add an @Modifying
to the method.
Be sure you are aware of the side effects of the approach you chose:
EntityManager
caches. Thus a subsequent findOne(…)
might/will still return the old instance of the object you tried to delete in case the EntityManager
had already loaded it. To prevent that, set the clearAutomatically
flag in @Modifying
to true
but be aware that this will cause all pending changes being wiped out.@PreUpdate
event will not get notified. Also any cascade operationsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With