Is there a way to return a list of objects from a MySQL stored procedure to JPA?

StackOverflow https://stackoverflow.com/questions/21916966

  •  14-10-2022
  •  | 
  •  

Вопрос

The procedure is:

CREATE PROCEDURE `hw1_db_1`.`r2_browse_movies_by_title`(IN str_title VARCHAR(200))
BEGIN
   SELECT * FROM `hw1_db_1`.`movies` WHERE title LIKE CONCAT('%', str_title, '%');
END

called in a Stateless EJB:

public List<Movie> searchTitles(String query) {
    StoredProcedureQuery nq = em
        .createStoredProcedureQuery("r2_browse_movies_by_title");
    nq.registerStoredProcedureParameter("str_title", String.class,
        ParameterMode.IN);
    return nq.setParameter("str_title", query).getResultList(); // unchecked cast
}

Unfortunately it does not return a List<Movie> but a List<Object[]> with the movie attributes. Any way to return a List<Movie> ? Any programmatic way to convert ?

Это было полезно?

Решение

I assume

    EntityManager.createStoredProcedureQuery(String procedureName, Class... resultClasses)
Create an instance of StoredProcedureQuery for executing a stored procedure in the database.

Just try passing the resultClasses to you entities.

The resultClass arguments must be specified in the order in which the result sets will be returned by the stored procedure invocation.

Parameters: procedureName - name of the stored procedure in the database resultClasses - classes to which the result sets produced by the stored procedure are to be mapped

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top