How can I write SQL query in JPA repository with Spring Boot?

I’m doing a spring boot experiment and using MySQL.

For example, if I have a list of users, but I want to get the specified names, how can I write the SQL query that only indicates this situation?

This is my model class :

public class User {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;
    public String name;
    @Column (name="last_name")
    public String last_name;

This is my JPA interface :

public interface CommentRepository extends JpaRepository<User , Long >{

  // All C.R.U.D database methods

Finally, my controller area is as below :

public class CommentController {
    CommentRepository repository ;
    public List<User> users() {
        return repository.findAll();

Maybe you didn’t understand my problem, I just want to write a customizable query of my own.

For example, I want to pull the data with the method I designed, while I normally pull the data by numbers with the find by id method.

>Solution :

You can either use methods that will be translated into queries or write your queries in the @Query annotation.

Please read the docs:

Leave a Reply