Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Last active February 2, 2020 18:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thjanssen/ee3319d11de0a44fd3bc to your computer and use it in GitHub Desktop.
Save thjanssen/ee3319d11de0a44fd3bc to your computer and use it in GitHub Desktop.
@NamedStoredProcedureQuery(
name = "calculate",
procedureName = "calculate",
parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, type = Double.class, name = "x"),
@StoredProcedureParameter(mode = ParameterMode.IN, type = Double.class, name = "y"),
@StoredProcedureParameter(mode = ParameterMode.OUT, type = Double.class, name = "sum")
}
)
CREATE OR REPLACE FUNCTION calculate(
IN x double precision,
IN y double precision,
OUT sum double precision)
RETURNS double precision AS
$BODY$
BEGIN
sum = x + y;
END;
$BODY$
LANGUAGE plpgsql
StoredProcedureQuery query = this.em.createNamedStoredProcedureQuery("calculate");
query.setParameter("x", 1.23d);
query.setParameter("y", 4.56d);
query.execute();
Double sum = (Double) query.getOutputParameterValue("sum");
List<Book> books = (List<Book>) this.em.createNamedStoredProcedureQuery("getBooks").getResultList();
List<Book> books = (List<Book>) this.em.createNamedStoredProcedureQuery("getBooks").getResultList();
for (Book b : books) {
StoredProcedureQuery q = this.em.createNamedStoredProcedureQuery("getReviews");
q.setParameter(2, b.getId());
List<Review> reviews = q.getResultList();
for (Review r : reviews) {
// do something
}
}
CREATE OR REPLACE FUNCTION get_books()
RETURNS refcursor AS
$BODY$
DECLARE
books refcursor; -- Declare cursor variables
BEGIN
OPEN books FOR SELECT id, publishingdate, title, version, publisher_id FROM book; -- Open a cursor
RETURN books; -- Return the cursor to the caller
END;
$BODY$
LANGUAGE plpgsql
CREATE OR REPLACE FUNCTION get_reviews(bookid bigint)
RETURNS refcursor AS
$BODY$
DECLARE
reviews refcursor; -- Declare cursor variables
BEGIN
OPEN reviews FOR SELECT id, comment, rating, version, book_id FROM review WHERE book_id = bookId;
RETURN reviews;
END;
$BODY$
LANGUAGE plpgsql
@NamedStoredProcedureQuery(
name = "getBooks",
procedureName = "get_books",
resultClasses = Book.class,
parameters = @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, type = void.class)
)
@NamedStoredProcedureQuery(
name = "getReviews",
procedureName = "get_reviews",
resultClasses = Review.class,
parameters = {
@StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, type = void.class),
@StoredProcedureParameter(mode = ParameterMode.IN, type = Long.class)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment