Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a stored procedure with hibernate criteria?

Can I use Hibernate criteria to call a stored procudure?

like image 881
Gaston Avatar asked Mar 25 '10 13:03

Gaston


People also ask

Can Hibernate call stored procedure?

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.

Is hibernate criteria deprecated?

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.

How do you call a function in hibernate?

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.


2 Answers

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>
like image 132
Lachlan Roche Avatar answered Oct 20 '22 20:10

Lachlan Roche


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;
    }

}
like image 5
Pascal Thivent Avatar answered Oct 20 '22 19:10

Pascal Thivent