Can I use Hibernate criteria to call a stored procudure?
Call a Stored Procedure With HibernateStarting from Hibernate 3, we have the possibility to use raw SQL statement including stored procedures to query a database. In this section, we are going to walk through a seemingly basic example that will illustrate how to call the GetAllFoos() procedure using Hibernate.
Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API. We'll explore how to use Hibernate and JPA to build Criteria Queries.
You can call Hibernate's @NamedNativeQuery in the same way as you call any other named query. You only need to call the createNamedQuery of your EntityManager with the name of the query, set all bind parameter values and call the getSingleResult or getResultList method. TypedQuery<Review> q = em.
See Using stored procedures for querying in the reference documentation.
Mapped queries are called like this.
List employment = sess.getNamedQuery("BigSP")
.list();
A mapped query can return entities.
<sql-query name="BigSP" callable="true">
<return alias="emp" class="Employment">
<return-property name="employee" column="EMPLOYEE"/>
<return-property name="employer" column="EMPLOYER"/>
<return-property name="startDate" column="STARTDATE"/>
<return-property name="endDate" column="ENDDATE"/>
<return-property name="regionCode" column="REGIONCODE"/>
<return-property name="id" column="EID"/>
<return-property name="salary">
<return-column name="VALUE"/>
<return-column name="CURRENCY"/>
</return-property>
</return>
{ call BigSP }
</sql-query>
No, you need to use a native query. If you are using annotations, see 2.3.2. Mapping native queries.
Below an example:
@Entity
@NamedNativeQuery(
name="baz",
query="call fooProc(:bar, :i)",
callable=true,
readOnly=true,
resultClass=Foo.class
)
public class Foo {
private Date when;
//...
}
And to call it:
@Stateless
public class FooBean implements FooLocal {
@PersistenceContext EntityManager em;
public Foo getAFoo(string bar, int i) {
Foo result = (Foo)em.createNamedQuery("baz").setParameter("bar", bar).setParameter("i", i).getSingleResult();
return result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With