如何使用Hibernate实现自定义String序列标识符生成器

dba5bblo  于 2023-05-18  发布在  其他
关注(0)|答案(3)|浏览(207)

我正在使用hibernate和spring,h2和liquibase,我试图通过这篇博客文章的例子为我的实体制作一个自定义的String id生成器,但我得到了一个错误:Caused by: org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String
下面是我的SequenceStyleGenerator代码:

public class CTCIDGenerator extends SequenceStyleGenerator {

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        if (obj instanceof Identifiable) {
            Identifiable identifiable = (Identifiable) obj;
            Serializable id = identifiable.getId();
            if (id != null) {
                return id;
            }
        }
        return "CTC"+super.generate(session, obj);
    }
}

我的实体代码:

@Entity
@Table(name = "contact")
public class Contact implements Serializable, Identifiable<String> {

    private static final long serialVersionUID = 1L;

    @Id
    @GenericGenerator(
        name = "assigned-sequence",
        strategy =     "net.atos.seirich.support.domain.idgenerator.CTCIDGenerator",
        parameters = @org.hibernate.annotations.Parameter(
            name = "sequence_name", 
            value = "hibernate_sequence"
        )
    )
    @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

liquibase XML:

<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

    <property name="autoIncrement" value="true" dbms="mysql,h2,postgresql,oracle"/>

    <property name="floatType" value="float4" dbms="postgresql, h2"/>
    <property name="floatType" value="float" dbms="mysql, oracle"/>

    <changeSet id="20160513091901-1" author="jhipster">
        <createTable tableName="contact">
            <column name="id" type="longvarchar" autoIncrement="${autoIncrement}">
                <constraints primaryKey="true" nullable="false"/>
            </column>
    </changeSet>
</databaseChangeLog>

顺便问一下,是否可以避免使用参数sequence_name,这样hibernate就可以自己处理了?
如果有人能帮助我,谢谢!

93ze6v8z

93ze6v8z1#

问题是SequenceStyleGenerator期望返回一个数值,而不是String
我已经试过解决这个问题的方法了,效果很好。因此,您需要像这样更改生成器:

public class StringSequenceIdentifier implements IdentifierGenerator, Configurable {

    private String sequenceCallSyntax;

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

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

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

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

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        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 "CTC" + seqValue;
    }
}

您的Map将变为:

@Entity(name = "Post")
@Table(name = "post")
public static class Post implements Identifiable<String> {

    @Id
    @GenericGenerator(
        name = "assigned-sequence",
        strategy = "com.vladmihalcea.book.hpjp.hibernate.identifier.StringSequenceIdentifier",
        parameters = @org.hibernate.annotations.Parameter(name = "sequence_name", value = "hibernate_sequence")
    )
    @GeneratedValue(generator = "assigned-sequence", strategy = GenerationType.SEQUENCE)
    private String id;

    @Version
    private Integer version;

    public Post() {
    }

    public Post(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }
}

现在,插入以下图元时:

doInJPA(entityManager -> {
    entityManager.persist(new Post());
    entityManager.persist(new Post("ABC"));
    entityManager.persist(new Post());
    entityManager.persist(new Post("DEF"));
});

Hibernate生成正确的标识符:

Query:["select nextval ('hibernate_sequence')"], Params:[()]
Query:["select nextval ('hibernate_sequence')"], Params:[()]
Query:["insert into post (version, id) values (?, ?)"], Params:[(0, CTC1)]
Query:["insert into post (version, id) values (?, ?)"], Params:[(0, ABC)]
Query:["insert into post (version, id) values (?, ?)"], Params:[(0, CTC2)]
Query:["insert into post (version, id) values (?, ?)"], Params:[(0, DEF)]

代码在GitHub上可用。

ilmyapht

ilmyapht2#

是的,hibernate有预建的String生成器。只需将您的@GenericGenerator定义替换为另一个策略。

@Entity
@Table(name = "contact")
public class Contact implements Serializable, Identifiable<String> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

要了解更多关于不同的hibernate生成器的信息,可以查看documentation

bwitn5fc

bwitn5fc3#

可以通过以下解决方案重用序列样式生成器

public class AppIdGenerator extends SequenceStyleGenerator {

    public static final String PREFIX_PARAM = "prefix";
    private String prefix;

    @Override
    public void configure(Type type, Properties properties,
                          ServiceRegistry serviceRegistry) throws MappingException {
        super.configure(new NamedBasicTypeImpl<>(new JavaTypeBasicAdaptor<>(Long.class),
                NumericJdbcType.INSTANCE, "long"), properties, serviceRegistry);
        prefix = StringUtils.capitalize(ConfigurationHelper.getString(PREFIX_PARAM, properties));
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
        return String.format("%s%09d", prefix, ((Long) super.generate(session, obj)));
    }
}

和实体

@Data
@EqualsAndHashCode(callSuper = false)
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = Subject.NAME, uniqueConstraints = {@UniqueConstraint(name = "UC_SUBJECT",
        columnNames = {"STUDY_KEY", "SUBJECT_UNIQUEID", "SUBJECT_UNIQUEID_SOURCE"})})
public class Subject extends Auditing {

  static final String NAME = "SUBJECT";

  static final String PREF = "SUBJ";

  @Id
  @GeneratedValue(generator = "subject_gen", strategy = GenerationType.SEQUENCE)
  @GenericGenerator(name = "subject_gen", strategy = "com.awesome.db.AppIdGenerator", parameters = {
          @org.hibernate.annotations.Parameter(name = "prefix", value = Subject.PREF),
          @org.hibernate.annotations.Parameter(name = "sequence_name", value = Subject.NAME + SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX),
          @org.hibernate.annotations.Parameter(name = "increment_size", value = "1")
          //@org.hibernate.annotations.Parameter(name = "initial_value", value = "21"),
          //@org.hibernate.annotations.Parameter(name = "optimizer", value = "pooled-lo"),
  })
  @Column(name = "SUBJECT_KEY", unique = true, nullable = false, updatable = false, length = 13)
  private String subjectKey;

  @ManyToOne(optional = false)
  @JoinColumn(name = "STUDY_KEY", referencedColumnName = "STUDY_KEY", foreignKey = @ForeignKey(name = "FK_STUDY_KEY"),
      nullable = false, updatable = false)
  private Study study;

  @NotNull
  @Column(name = "SUBJECT_UNIQUEID", length = 120)
  private String subjectId;

  @NotNull
  @Column(name = "SUBJECT_UNIQUEID_SOURCE", length = 120)
  private String subjectIdSource;
}

结果:
1.使用数字数据库序列计数器
1.支持数据库结构和集成优化程序的选项
请记住,如果您使用任何填充脚本,如 import.sql/data.sql,则initial_value参数必须手动与表中的行数同步(硬编码或从外部应用程序提供)或nextval采用id字符串键格式

--import.sql
INSERT INTO SUBJECT (subject_key, subject_uniqueid, subject_uniqueid_source, created_date, modified_date, study_key) VALUES('SUBJ'||to_char(nextval('subject_seq'), 'FM000000009'),'1234','Other.App','2023-05-17 14:05:46.521000','2023-05-17 14:05:46.521000','STUD000000001');

相关问题