filippo.derosa84
filippo.derosa84

Reputation: 126

Hibernate 5: createNativeQuery() in Singleton pattern

I have a DAO class which internally is querying the next_val from an Oracle sequence.

As this sequence is not bound to any entities, but simply querying the value for internal logic, I'm creating the native query every time the getNextValueFromSequence() method is invoked on the DAO as follows:

Query nextValQuery = entityManager.createNativeQuery(GET_NEXT_SEQUENCE_VAL_SQL);

As I'm creating the query every time the method is invoked, I was thinking to refactor this to have the native query created in a singleton defined as a Spring bean, so that the query gets created only the first time my getNextValueFromSequence() it's invoked.

Is there any drawback in doing this? Would the Hibernate session give problems with this approach?

Upvotes: 1

Views: 541

Answers (2)

hunter
hunter

Reputation: 4183

Query instance is bounded to the session, so it is not good idea to reuse the same Query instance.

Upvotes: 0

Maciej Kowalski
Maciej Kowalski

Reputation: 26552

I would recommend taking advantage of named query feature provided by thet JPA specification:

@Entity
@NamedNativeQuery(name = "sequenceQuery", query = "<query>", resultClass = Integer.class)

The annotation has to be defined on some entity.

Then you get the query as follows:

Query nextValQuery = entityManager.createNamedQuery("sequenceQuery");

Thanks to that the query will be created only once during startup of the application.

Upvotes: 1

Related Questions