In Grails / Hibernate Can you set the generator to increase only if it is not assigned?

Is there a way to use hibernate automatically generated identifiers if it was not assigned, but to use the assigned value if it was?

+3
source share
1 answer

I believe that for this there is no ready-made solution in Grails, but it should be quite simple to implement your own org.hibernate.id.IdentifierGenerator.

By implementing this interface, you delegate your default identifier generation strategy until no identifier is assigned, otherwise use the already assigned value of your domain object.

IdentityGenerator, , :

package my.company.hibernate

import org.hibernate.engine.SessionImplementor

public class PreAssignedIdGenerator extends org.hibernate.id.IdentityGenerator {
  public Serializable generate(SessionImplementor session, Object object) {
    return object.id ? object.id : super.generate(session, object)
  }
}

id:

class FooDomain { 
  Long id
  static mapping = {
    id generator: "my.company.hibernate.PreAssignedIdGenerator"
  }
}
+3

Source: https://habr.com/ru/post/1750056/


All Articles