1

I'm getting the "No data type for node" error when I run this query:

session.createQuery("select nextval( 'next_num_seq' )")

which I know means that I need to make it a property of a class, but I haven't been able to find a way to add a sequence to a class, only how to make a sequence generate IDs for a class.

Is there a way to include a sequence in a Hibernate mapping that isn't an ID generator?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
user3413468
  • 247
  • 1
  • 3
  • 9

1 Answers1

2

As such, this question is valid, yet the path to the solution is headed in the wrong direction. Mapping a Sequence into a managed domain entity is not a "good" idea, as these are two separate concepts.

Sequences, such as the one you are trying to query from a PostgreSQL backend, are a central concept for the generation of unique IDs for primary key values of tuples or - from an ORM application perspective - Java objects. Thus, it is not clever to map their current state to a domain entity. Instead, one sets a single, particular value drawn from such a sequence - e.g. next_num_seq - into one particular object to be persisted in a relational database. Therefore, the related class of such an domain object is linked to this sequence by, for instance, dedicated ORM annotations (or via similar approaches).

In the JavaDoc of the Session interface we find the method createNativeQuery(String sql) which is inherited from the EntityManager interface, see also here.

It is described as follows:

Query createNativeQuery(java.lang.String sqlString)

Create an instance of Query for executing a native SQL statement, e.g., for update or delete.

Parameters: sqlString - a native SQL query string

Returns: the new query instance

Thus, you could modify your code to execute the native query against your PostgreSQL database as follows:

Query q = session.createNativeQuery("select nextval( 'next_num_seq' )");

This gives you the option to read the next valid sequence value as a long or Number instance for your programming purposes.

Note well: Be careful not to reuse this value multiple times (for several objects), as this might cause consistency trouble in your backend when used, for instance, in the context of separate threads.

Hope this helps.

MWiesner
  • 8,868
  • 11
  • 36
  • 70