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);
}
}


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading