Search code examples
javahibernatenativequery

Hibernate 5.2 Native Query with void function Postgresql


I'm a beginner with hibernate. I have a void function in PostgreSQL with 10 arguments (it's a "create or update" function) and I want to use it in my application.

I read that doing a Native Query is the simplest way.

So I wrote this code:

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

String a = "SELECT fun('text', 'text', 12345678987, 'text', 'text', 50, 37500, 133456788, 'text', 2);
session.createNativeQuery(a);

session.getTransaction().commit();
session.close();

The application starts without any errors, but when I check the database I don't have new record.

Can someone explain what is wrong? Should I do something else with the function?


Solution

  • When I check database I don't have new rekord Ofc you don't, you are doing a SELECT, so you're not doing anything in your database.

    Also in order to execute your query you don't need to open any transaction since you are not inserting/updating/deleting anything, and you need to do the following to get the result:

    session.createNativeQuery(a).getResultList() if you expect multiple results from this query

    session.createNativeQuery(a).getSingleResult() if you expect only one result.

    session.createNativeQuery(a).executeUpdate() if you're actually inserting/updating/deleting something, in that case you will need the transaction like you did in your code.