Annotation Type SQL

  • @Target(METHOD)
    public @interface SQL
    Identifies a method of an abstract class or interface as defining the signature of a method which is used to execute the given SQL query, with an implementation generated automatically by the Hibernate Metamodel Generator.

    For example:

     public interface Books {
         @SQL("select * from Book where isbn = :isbn")
         Book findBookByIsbn(String isbn);
         @SQL("select * from Book where title like ?1 order by title offset ?3 fetch first ?2 rows only")
         List<Book> findBooksByTitleWithPagination(String title, int max, int start);
         @SQL("select * from Book where title like ?1")
         Query findBooksByTitle(String title);

    The Metamodel Generator automatically creates an "implementation" of these methods in the static metamodel class Books_. The generated methods may be called according to the following protocol:

     Book book = Books_.findBookByIsbn(session, isbn);
     List<Book> books = Books_.findBooksByTitleWithPagination(session, pattern, 10, 0);

    Notice the extra parameter of type EntityManager at the start of the parameter list.

    Alternatively, the type to which the annotated method belongs may also declare an abstract method with no parameters which returns one of the types EntityManager, Session, StatelessSession, or Mutiny.Session, for example:

     EntityManager entityManager();
    In this case:
    • the generated method is no longer static,
    • the generated method will use this method to obtain the session object, instead of having a parameter of type EntityManager, and
    • the generated static metamodel class will actually implement the type which declares the method annotated @SQL.

    Thus, the generated methods may be called according to the following protocol:

     Books books = new Books_(session);
     Book book = books.findBookByIsbn(isbn);
     List<Book> books = books.findBooksByTitleWithPagination(pattern, 10, 0);

    This is reminiscent of traditional DAO-style repositories.

    The return type of an annotated method must be:

    The method parameters must match the parameters of the SQL query, either by name or by position:

    • an ordinal query parameter of form ?n is matched to the nth parameter of the method, and
    • a named query parameter of form :name is matched to the method parameter name.

    As an exception, the method may have at most one parameter of type EntityManager, Session, StatelessSession, or Mutiny.Session.

    See Also:
    HQL, Find
    • Required Element Summary

      Required Elements 
      Modifier and Type Required Element Description
      String value