String increment for alphanumeric field is for JPA not working












0














https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/



i tried to this for a field that is not primary key.



Also same solution for here:
How to implement IdentifierGenerator with PREFIX and separate Sequence for each entity



But even it does not go to Java method when i run the program. It saves as null.



And i cant see the log that i put inside my class. There is no log for my class.



I copied from that blog but my code is:



public class StringSequenceIdentifier
implements IdentifierGenerator, Configurable {

public static final String SEQUENCE_PREFIX = "sequence_prefix";

private String sequencePrefix;

private String sequenceCallSyntax;

@Override
public void configure(
Type type, Properties params, ServiceRegistry serviceRegistry)
throws MappingException {
System.out.println("xxx");
final JdbcEnvironment jdbcEnvironment =
serviceRegistry.getService(JdbcEnvironment.class);
final Dialect dialect = jdbcEnvironment.getDialect();

final ConfigurationService configurationService =
serviceRegistry.getService(ConfigurationService.class);
String globalEntityIdentifierPrefix =
configurationService.getSetting( "entity.identifier.prefix", String.class, "SEQ_" );

sequencePrefix = ConfigurationHelper.getString(
SEQUENCE_PREFIX,
params,
globalEntityIdentifierPrefix);

final String sequencePerEntitySuffix = ConfigurationHelper.getString(
SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
params,
SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

final String defaultSequenceName = ConfigurationHelper.getBoolean(
SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
params,
false)
? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
: SequenceStyleGenerator.DEF_SEQUENCE_NAME;

sequenceCallSyntax = dialect.getSequenceNextValString(
ConfigurationHelper.getString(
SequenceStyleGenerator.SEQUENCE_PARAM,
params,
defaultSequenceName));
}

@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) {
System.out.println("xxx");
if (obj instanceof Identifiable) {
Identifiable identifiable = (Identifiable) obj;
Serializable id = identifiable.getId();
if (id != null) {
return id;
}
}
long seqValue = ((Number) Session.class.cast(session)
.createSQLQuery(sequenceCallSyntax)
.uniqueResult()).longValue();

return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
}
}


That is in my domain:



@GenericGenerator(
name = "assigned-sequence",
strategy = "xxxxxx.StringSequenceIdentifier",
parameters = {
@org.hibernate.annotations.Parameter(
name = "sequence_name", value = "hibernate_sequence"),
@org.hibernate.annotations.Parameter(
name = "sequence_prefix", value = "CTC_"),
}
)
@GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
private String referenceCode;


WHAT I WANT IS
I need a unique field, which is not primary. So, i decided that incrementing is best solution because otherwise, i have to check for each created random if it exists in database (i also open suggestions for this).



It will be around 5-6 characters and alphanumeric.



I want to make JPA increment this but it seems i cant do it.










share|improve this question



























    0














    https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/



    i tried to this for a field that is not primary key.



    Also same solution for here:
    How to implement IdentifierGenerator with PREFIX and separate Sequence for each entity



    But even it does not go to Java method when i run the program. It saves as null.



    And i cant see the log that i put inside my class. There is no log for my class.



    I copied from that blog but my code is:



    public class StringSequenceIdentifier
    implements IdentifierGenerator, Configurable {

    public static final String SEQUENCE_PREFIX = "sequence_prefix";

    private String sequencePrefix;

    private String sequenceCallSyntax;

    @Override
    public void configure(
    Type type, Properties params, ServiceRegistry serviceRegistry)
    throws MappingException {
    System.out.println("xxx");
    final JdbcEnvironment jdbcEnvironment =
    serviceRegistry.getService(JdbcEnvironment.class);
    final Dialect dialect = jdbcEnvironment.getDialect();

    final ConfigurationService configurationService =
    serviceRegistry.getService(ConfigurationService.class);
    String globalEntityIdentifierPrefix =
    configurationService.getSetting( "entity.identifier.prefix", String.class, "SEQ_" );

    sequencePrefix = ConfigurationHelper.getString(
    SEQUENCE_PREFIX,
    params,
    globalEntityIdentifierPrefix);

    final String sequencePerEntitySuffix = ConfigurationHelper.getString(
    SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
    params,
    SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

    final String defaultSequenceName = ConfigurationHelper.getBoolean(
    SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
    params,
    false)
    ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
    : SequenceStyleGenerator.DEF_SEQUENCE_NAME;

    sequenceCallSyntax = dialect.getSequenceNextValString(
    ConfigurationHelper.getString(
    SequenceStyleGenerator.SEQUENCE_PARAM,
    params,
    defaultSequenceName));
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) {
    System.out.println("xxx");
    if (obj instanceof Identifiable) {
    Identifiable identifiable = (Identifiable) obj;
    Serializable id = identifiable.getId();
    if (id != null) {
    return id;
    }
    }
    long seqValue = ((Number) Session.class.cast(session)
    .createSQLQuery(sequenceCallSyntax)
    .uniqueResult()).longValue();

    return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
    }
    }


    That is in my domain:



    @GenericGenerator(
    name = "assigned-sequence",
    strategy = "xxxxxx.StringSequenceIdentifier",
    parameters = {
    @org.hibernate.annotations.Parameter(
    name = "sequence_name", value = "hibernate_sequence"),
    @org.hibernate.annotations.Parameter(
    name = "sequence_prefix", value = "CTC_"),
    }
    )
    @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
    private String referenceCode;


    WHAT I WANT IS
    I need a unique field, which is not primary. So, i decided that incrementing is best solution because otherwise, i have to check for each created random if it exists in database (i also open suggestions for this).



    It will be around 5-6 characters and alphanumeric.



    I want to make JPA increment this but it seems i cant do it.










    share|improve this question

























      0












      0








      0







      https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/



      i tried to this for a field that is not primary key.



      Also same solution for here:
      How to implement IdentifierGenerator with PREFIX and separate Sequence for each entity



      But even it does not go to Java method when i run the program. It saves as null.



      And i cant see the log that i put inside my class. There is no log for my class.



      I copied from that blog but my code is:



      public class StringSequenceIdentifier
      implements IdentifierGenerator, Configurable {

      public static final String SEQUENCE_PREFIX = "sequence_prefix";

      private String sequencePrefix;

      private String sequenceCallSyntax;

      @Override
      public void configure(
      Type type, Properties params, ServiceRegistry serviceRegistry)
      throws MappingException {
      System.out.println("xxx");
      final JdbcEnvironment jdbcEnvironment =
      serviceRegistry.getService(JdbcEnvironment.class);
      final Dialect dialect = jdbcEnvironment.getDialect();

      final ConfigurationService configurationService =
      serviceRegistry.getService(ConfigurationService.class);
      String globalEntityIdentifierPrefix =
      configurationService.getSetting( "entity.identifier.prefix", String.class, "SEQ_" );

      sequencePrefix = ConfigurationHelper.getString(
      SEQUENCE_PREFIX,
      params,
      globalEntityIdentifierPrefix);

      final String sequencePerEntitySuffix = ConfigurationHelper.getString(
      SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
      params,
      SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

      final String defaultSequenceName = ConfigurationHelper.getBoolean(
      SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
      params,
      false)
      ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
      : SequenceStyleGenerator.DEF_SEQUENCE_NAME;

      sequenceCallSyntax = dialect.getSequenceNextValString(
      ConfigurationHelper.getString(
      SequenceStyleGenerator.SEQUENCE_PARAM,
      params,
      defaultSequenceName));
      }

      @Override
      public Serializable generate(SharedSessionContractImplementor session, Object obj) {
      System.out.println("xxx");
      if (obj instanceof Identifiable) {
      Identifiable identifiable = (Identifiable) obj;
      Serializable id = identifiable.getId();
      if (id != null) {
      return id;
      }
      }
      long seqValue = ((Number) Session.class.cast(session)
      .createSQLQuery(sequenceCallSyntax)
      .uniqueResult()).longValue();

      return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
      }
      }


      That is in my domain:



      @GenericGenerator(
      name = "assigned-sequence",
      strategy = "xxxxxx.StringSequenceIdentifier",
      parameters = {
      @org.hibernate.annotations.Parameter(
      name = "sequence_name", value = "hibernate_sequence"),
      @org.hibernate.annotations.Parameter(
      name = "sequence_prefix", value = "CTC_"),
      }
      )
      @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
      private String referenceCode;


      WHAT I WANT IS
      I need a unique field, which is not primary. So, i decided that incrementing is best solution because otherwise, i have to check for each created random if it exists in database (i also open suggestions for this).



      It will be around 5-6 characters and alphanumeric.



      I want to make JPA increment this but it seems i cant do it.










      share|improve this question













      https://vladmihalcea.com/how-to-implement-a-custom-string-based-sequence-identifier-generator-with-hibernate/



      i tried to this for a field that is not primary key.



      Also same solution for here:
      How to implement IdentifierGenerator with PREFIX and separate Sequence for each entity



      But even it does not go to Java method when i run the program. It saves as null.



      And i cant see the log that i put inside my class. There is no log for my class.



      I copied from that blog but my code is:



      public class StringSequenceIdentifier
      implements IdentifierGenerator, Configurable {

      public static final String SEQUENCE_PREFIX = "sequence_prefix";

      private String sequencePrefix;

      private String sequenceCallSyntax;

      @Override
      public void configure(
      Type type, Properties params, ServiceRegistry serviceRegistry)
      throws MappingException {
      System.out.println("xxx");
      final JdbcEnvironment jdbcEnvironment =
      serviceRegistry.getService(JdbcEnvironment.class);
      final Dialect dialect = jdbcEnvironment.getDialect();

      final ConfigurationService configurationService =
      serviceRegistry.getService(ConfigurationService.class);
      String globalEntityIdentifierPrefix =
      configurationService.getSetting( "entity.identifier.prefix", String.class, "SEQ_" );

      sequencePrefix = ConfigurationHelper.getString(
      SEQUENCE_PREFIX,
      params,
      globalEntityIdentifierPrefix);

      final String sequencePerEntitySuffix = ConfigurationHelper.getString(
      SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX,
      params,
      SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX);

      final String defaultSequenceName = ConfigurationHelper.getBoolean(
      SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY,
      params,
      false)
      ? params.getProperty(JPA_ENTITY_NAME) + sequencePerEntitySuffix
      : SequenceStyleGenerator.DEF_SEQUENCE_NAME;

      sequenceCallSyntax = dialect.getSequenceNextValString(
      ConfigurationHelper.getString(
      SequenceStyleGenerator.SEQUENCE_PARAM,
      params,
      defaultSequenceName));
      }

      @Override
      public Serializable generate(SharedSessionContractImplementor session, Object obj) {
      System.out.println("xxx");
      if (obj instanceof Identifiable) {
      Identifiable identifiable = (Identifiable) obj;
      Serializable id = identifiable.getId();
      if (id != null) {
      return id;
      }
      }
      long seqValue = ((Number) Session.class.cast(session)
      .createSQLQuery(sequenceCallSyntax)
      .uniqueResult()).longValue();

      return sequencePrefix + String.format("%011d%s", 0 ,seqValue);
      }
      }


      That is in my domain:



      @GenericGenerator(
      name = "assigned-sequence",
      strategy = "xxxxxx.StringSequenceIdentifier",
      parameters = {
      @org.hibernate.annotations.Parameter(
      name = "sequence_name", value = "hibernate_sequence"),
      @org.hibernate.annotations.Parameter(
      name = "sequence_prefix", value = "CTC_"),
      }
      )
      @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
      private String referenceCode;


      WHAT I WANT IS
      I need a unique field, which is not primary. So, i decided that incrementing is best solution because otherwise, i have to check for each created random if it exists in database (i also open suggestions for this).



      It will be around 5-6 characters and alphanumeric.



      I want to make JPA increment this but it seems i cant do it.







      java spring-data-jpa






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 6:42









      vegan

      167




      167
























          1 Answer
          1






          active

          oldest

          votes


















          1














          This is very similar to Hibernate JPA Sequence (non-Id) but I don't think it's an exact duplicate. Yet the answers seem to apply and they seem to suggest the following strategies:




          1. Make the field to be generated a reference to an entity with the only purpose that the field now becomes an ID and can get generated by the usual strategies. https://stackoverflow.com/a/536102/66686


          2. Use @PrePersist to fill the field before it gets persisted. https://stackoverflow.com/a/35888326/66686


          3. Make it @Generated and generate the value in the database using a trigger or similar. https://stackoverflow.com/a/283603/66686







          share|improve this answer





















          • Step 3 suggests a xml and from 2008. Is there another way for it?
            – vegan
            Nov 12 at 11:07










          • In the comment to that answer, @Generated is given as the annotation based equivalent.
            – Jens Schauder
            Nov 12 at 12:00










          • And could not understand 3. solution. How can i add prefix to that
            – vegan
            Nov 14 at 20:57











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257057%2fstring-increment-for-alphanumeric-field-is-for-jpa-not-working%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          This is very similar to Hibernate JPA Sequence (non-Id) but I don't think it's an exact duplicate. Yet the answers seem to apply and they seem to suggest the following strategies:




          1. Make the field to be generated a reference to an entity with the only purpose that the field now becomes an ID and can get generated by the usual strategies. https://stackoverflow.com/a/536102/66686


          2. Use @PrePersist to fill the field before it gets persisted. https://stackoverflow.com/a/35888326/66686


          3. Make it @Generated and generate the value in the database using a trigger or similar. https://stackoverflow.com/a/283603/66686







          share|improve this answer





















          • Step 3 suggests a xml and from 2008. Is there another way for it?
            – vegan
            Nov 12 at 11:07










          • In the comment to that answer, @Generated is given as the annotation based equivalent.
            – Jens Schauder
            Nov 12 at 12:00










          • And could not understand 3. solution. How can i add prefix to that
            – vegan
            Nov 14 at 20:57
















          1














          This is very similar to Hibernate JPA Sequence (non-Id) but I don't think it's an exact duplicate. Yet the answers seem to apply and they seem to suggest the following strategies:




          1. Make the field to be generated a reference to an entity with the only purpose that the field now becomes an ID and can get generated by the usual strategies. https://stackoverflow.com/a/536102/66686


          2. Use @PrePersist to fill the field before it gets persisted. https://stackoverflow.com/a/35888326/66686


          3. Make it @Generated and generate the value in the database using a trigger or similar. https://stackoverflow.com/a/283603/66686







          share|improve this answer





















          • Step 3 suggests a xml and from 2008. Is there another way for it?
            – vegan
            Nov 12 at 11:07










          • In the comment to that answer, @Generated is given as the annotation based equivalent.
            – Jens Schauder
            Nov 12 at 12:00










          • And could not understand 3. solution. How can i add prefix to that
            – vegan
            Nov 14 at 20:57














          1












          1








          1






          This is very similar to Hibernate JPA Sequence (non-Id) but I don't think it's an exact duplicate. Yet the answers seem to apply and they seem to suggest the following strategies:




          1. Make the field to be generated a reference to an entity with the only purpose that the field now becomes an ID and can get generated by the usual strategies. https://stackoverflow.com/a/536102/66686


          2. Use @PrePersist to fill the field before it gets persisted. https://stackoverflow.com/a/35888326/66686


          3. Make it @Generated and generate the value in the database using a trigger or similar. https://stackoverflow.com/a/283603/66686







          share|improve this answer












          This is very similar to Hibernate JPA Sequence (non-Id) but I don't think it's an exact duplicate. Yet the answers seem to apply and they seem to suggest the following strategies:




          1. Make the field to be generated a reference to an entity with the only purpose that the field now becomes an ID and can get generated by the usual strategies. https://stackoverflow.com/a/536102/66686


          2. Use @PrePersist to fill the field before it gets persisted. https://stackoverflow.com/a/35888326/66686


          3. Make it @Generated and generate the value in the database using a trigger or similar. https://stackoverflow.com/a/283603/66686








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 at 9:43









          Jens Schauder

          45.7k17112235




          45.7k17112235












          • Step 3 suggests a xml and from 2008. Is there another way for it?
            – vegan
            Nov 12 at 11:07










          • In the comment to that answer, @Generated is given as the annotation based equivalent.
            – Jens Schauder
            Nov 12 at 12:00










          • And could not understand 3. solution. How can i add prefix to that
            – vegan
            Nov 14 at 20:57


















          • Step 3 suggests a xml and from 2008. Is there another way for it?
            – vegan
            Nov 12 at 11:07










          • In the comment to that answer, @Generated is given as the annotation based equivalent.
            – Jens Schauder
            Nov 12 at 12:00










          • And could not understand 3. solution. How can i add prefix to that
            – vegan
            Nov 14 at 20:57
















          Step 3 suggests a xml and from 2008. Is there another way for it?
          – vegan
          Nov 12 at 11:07




          Step 3 suggests a xml and from 2008. Is there another way for it?
          – vegan
          Nov 12 at 11:07












          In the comment to that answer, @Generated is given as the annotation based equivalent.
          – Jens Schauder
          Nov 12 at 12:00




          In the comment to that answer, @Generated is given as the annotation based equivalent.
          – Jens Schauder
          Nov 12 at 12:00












          And could not understand 3. solution. How can i add prefix to that
          – vegan
          Nov 14 at 20:57




          And could not understand 3. solution. How can i add prefix to that
          – vegan
          Nov 14 at 20:57


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257057%2fstring-increment-for-alphanumeric-field-is-for-jpa-not-working%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          The Sandy Post

          Danny Elfman

          Pages that link to "Head v. Amoskeag Manufacturing Co."