How to write Native SQL Queries in Spring boot

Sometimes we have some constraints where we aren’t able to use the JPA or Query Method in our Repository class in Spring boot So we need to go back to basics and need to write the native SQL query to achieve the solution.

In Today’s Tutorial, we will see how to write Native SQL Query in Repository Class.

See our Entity Class

public class Student{

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(name="student_name")
private String name;

@Column(name="age")
private Integer age;

//getter & setters

}

Now our Repository Class would be something like below

@Repository
public interface StudentRepository extends JpaRepository<Student,Long>{

      Student  findById(Long id);
      

      //Native Query Method of number of student of given name
      @Query(value="select count(1) from student where student_name = :name" ,nativeQuery=true )
      Integer NumberOfStudent(@Param("name") String name);


}

Points to be noted here –

  • We need to use the actual column name in where clause when we use the native SQL query way.
    • In the above class, if you see the student_name is column name ( whereas name is defined in entity class ) we use student_name rather name.
  • we should use the actual table name rather than the Entity class name in native SQL queries.

 

If you have any specific issue which you are encountering in your project and wasn’t able to solve, leave us a comment we will try to help you.

Thanks for reading

Noeik.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *