Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="users")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;
    
    @Column(name="first_name")
    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 :

@RestController
@RequestMapping(path="/api/v1/users")
public class CommentController {
    
    @Autowired
    CommentRepository repository ;
    
    @GetMapping(path="/list")
    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: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading