在休眠中创建自定义ID生成器的问题

时间:2019-02-14 12:06:45

标签: java hibernate spring-boot jpa

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;
}

}

期望的输出是主要ID为str_00001,str_00002 ....

1 个答案:

答案 0 :(得分:0)

我可以提供可能对您有所帮助的基于注释的Java配置。 您应该用@Entity注释类,以便让休眠管理它,然后用@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
}