проблема создания генератора пользовательских идентификаторов в спящем режиме - PullRequest
0 голосов
/ 14 февраля 2019
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.usermanagement.model.Employee]
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.finicspro.usermanagement.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:32)
    at com.finicspro.usermanagement.util.HibernateUtil.getSessionFactory(HibernateUtil.java:58)
    at com.usermanagement.HibernateMain.main(HibernateMain.java:25)
Caused by: org.hibernate.MappingException: Could not instantiate id generator [entity-name=com.usermanagement.model.Employee]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:124)
    at org.hibernate.mapping.SimpleValue.createIdentifierGenerator(SimpleValue.java:342)
    at org.hibernate.internal.SessionFactoryImpl.lambda$new$1(SessionFactoryImpl.java:281)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.util.stream.ReferencePipeline$2$1.accept(Unknown Source)
    at java.util.HashMap$ValueSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:280)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at com.finicspro.usermanagement.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:26)
    ... 2 more
Caused by: org.hibernate.MappingException: Could not interpret id generator strategy [com.customid.EmployeeIdGenerator]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.getIdentifierGeneratorClass(DefaultIdentifierGeneratorFactory.java:144)
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.createIdentifierGenerator(DefaultIdentifierGeneratorFactory.java:115)
    ... 18 more

EmployeeIdGenerator.java

public class EmployeeIdGenerator extends SequenceStyleGenerator {


 public static final String VALUE_PREFIX_PARAMETER = "valuePrefix";
 public static final String VALUE_PREFIX_DEFAULT = "str_";
 private String valuePrefix;
 public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
 public static final String NUMBER_FORMAT_DEFAULT = "%05d";
 private String numberFormat;

 @Override
 public Serializable generate(SharedSessionContractImplementor session,
         Object object) throws HibernateException {
     return valuePrefix + String.format(numberFormat, 
               super.generate(session, object));
 }

 @Override
 public void configure(Type type, Properties params,
         ServiceRegistry serviceRegistry) throws MappingException {
     super.configure(LongType.INSTANCE, params, serviceRegistry);
     valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER,
             params, VALUE_PREFIX_DEFAULT);
     numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
             params, NUMBER_FORMAT_DEFAULT);
 }
}

Employee.java

public class Employee {

private String id;
private String name;
private String role;


public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getRole() {
    return role;
}
public void setRole(String role) {
    this.role = role;
}

}

ожидаемый вывод - первичный идентификатор: str_00001, str_00002 ....

1 Ответ

0 голосов
/ 28 февраля 2019

Я могу предоставить основанную на аннотации конфигурацию Java, которая, возможно, может помочь.Вы должны аннотировать свой класс с помощью @Entity, чтобы позволить hibernate управлять им, затем аннотировать идентификатор с помощью @Id и навязывать использовать ваш собственный генератор, используя @GenericGenerator и @GeneratedValues, что-то вроде этого:

public class Employee {

       @Id
       @GenericGenerator(name = "generator_name", 
                  strategy = "com.yourpackage.EmployeeIdGenerator ", 
                  parameters = {
                            @Parameter(name = "sequence_name", value = "your_sequence"),
                            @Parameter(name = StringPrefixedSequenceIdGenerator.VALUE_PREFIX_PARAMETER, value = "str_"),
                            @Parameter(name = StringPrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "50") 
                  }
        )
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator_name")
        private String id;
        private String name;
        private String role;

        //omitting getters and setters for brevity
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...