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 .

STEP 1:

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

STEP 2:

  • 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>{
   
   @Transactional
   @Modifying
   void deleteByField1andField2(String field1, String field2);
}

STEP 3:

Finally in the client code invoke the repository method :

@Component
public class Client{

  @Autowired
  private YourRepository repository;

  public void deleteRecord(final String field1Value,final String field2Value){
   this.repository.deleteByField1andField2(field1Value,field2Value);
}
}

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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