How to delete records in Spring Data based on multiple field values?

Spring Data has made it so easy to deal with database. Most boiler plate code are removed and user can just concentrate on the business logic.

Here is a simple way to delete records using multiple field values from a relational database table .


  • Prepare your entity which corresponds to the table.
  • Write a named query on top of the entity class as shown below
@NamedQuery(name="YourEntity.deleteByField1andField2" , query="delete from YourEntity y where y.field1 = ?1 and y.field2 = ?2")
public class YourEntity extends Serializable{
   private long id;
   private String field1;
   private String field2;


  • Prepare your repository by extending CrudRepository provided by spring data
  • Declare an abstract method using the same name as the named query used in the entity
  • Mark the method as @Transactional
  • Mark the method as @Modifying
  • Return only void :

public class YourRepository extends CrudRepository<YourEntity,long>{
   void deleteByField1andField2(String field1, String field2);


Finally in the client code invoke the repository method :

public class Client{

  private YourRepository repository;

  public void deleteRecord(final String field1Value,final String field2Value){

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s