I need to query a function of the database, by SQL, something so simple as
@Query("SELECT random()")
how to implement a domain/repository or service method that do it?
I need to query a function of the database, by SQL, something so simple as
@Query("SELECT random()")
how to implement a domain/repository or service method that do it?
There are various ways how to bind stored procedures with Spring Data JPA (using JPA 2.1).
Simplest example:
@Procedure("random")
Integer randomStoredProcedure();
In case, you don't have any Entity/DTO (non @Entity) objects and wondering how to map returned table from the function into your custom object.
@Repository
public class YourRepository {
private final EntityManager entityManager;
public(EntityManager entityManager) {
this.entityManager = entityManager;
}
public List<YourObject> findObjects() {
List<Object[]> columns = entityManager
.createStoredProcedureQuery("your_sql_func")
.getResultList();
return columns.stream().map(this::toYourObject).collect(Collectors.toList());
}
private YourObject toYourObject(Object[] columns) {
return new YourObject((int)columns[0], (String)columns[1]);
}
}
class YourObject {
private int number;
private String name;
public YourObject(int number, String name) {
this.number = number;
this.name = name;
}
// getters/setters or use Lombok
}
If you have any parameters in your function then your query should look like this,
List<Object[]> columns = entityManager
.createStoredProcedureQuery("your_sql_func")
.registerStoredProcedureParameter("param1Name", String.class, ParameterMode.IN)
.setParameter("param1Name", param1Value)
.getResultList();
You could use native query as well,
List<Object[]> columns = entityManager
.createNativeQuery("SELECT * FROM your_sql_func(:param1Name)")
.setParameter("param1Name", param1Value)
.getResultList();