Search code examples
hibernatepostgresqlgrailssequencepojo

sequence generator mapping for Grails POJO domain class


I have POJO domain class in Grails/PostgreSql app and I'm trying to map postgres sequence generatorg for its ID.

In POJO:

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "flight_id")
public long getId() {
    return id;
}

In Postgres:

-- Sequence: flight_id

-- DROP SEQUENCE flight_id;

CREATE SEQUENCE flight_id
  INCREMENT 1
  MINVALUE 1n 
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;
ALTER TABLE flight_id
  OWNER TO postgres;

When I try running grails generate-all for that domain I get:

 Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown Id.generator: flight_id

Everything else seems to working ok, except this. I'm trying to use Postres native generator so I have the option of running CRUD operations against the DB that is independent of the Grails app.

Any hints would be most appreciated.


Solution

  • There is two problems:

    1. usage of GenerationType.AUTO (persistence provider chooses strategy freely) when GenerationType.SEQUENCE seems to be preferred and
    2. false assumption that flight_id in generator = "flight_id" refers directly to the name of database sequence, when it actually refers to: (following directly from documentation):

      The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation

    What should be done is changing strategy to GenerationType.SEQUENCE and defining SequenceGenerator that is consistent with database sequence and does have same value for name attribute as is value of generator attribute in GeneratedValue.