I am new to springboot and facing issue in JPQL,nativeQuery. While doing read operation native query is working
@Query(value="select * from student s where s.name= :name", nativeQuery=true)
List<Student> getStudentByName(String name);
working but its not working when doing delete operation on database
@Query(value="delete from student s where s.name= :name",nativeQuery = true)
void deleteStudentByName(String name);
Entity Class
package com.example.demo.test.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Please help. Thank you
CodePudding user response:
Write operations need to be executed differently than read operations, you also need to annotate the repository method with a @Modifying annotation. Hence put @Modifying above the delete Query.
@Modifying
@Query(value="delete from student s where s.name= :name",nativeQuery = true)
void deleteStudentByName(String name);
I suggest you to not write nativeQuery and learn JPQL because
- Pagination of native query results requires an extra step.
- Spring Data JPA doesn’t support dynamic sorting for native SQL statements.
CodePudding user response:
Use can use the JPQL Query like void deleteByName(String name);
You can refer this link also : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords