一、前言
对于基于分布式数据库使用场景自定义实现主键序列生成器,从而实现跨数据库的表的序列一致性,这边基于Hibernate的org.hibernate.id.SequenceGenerator来实现自定义生成序列格式,当然通过UUID也是比较常见的实现方式。
二、代码示例
1.首先自定义StringSequenceGenerator来继承org.hibernate.id.SequenceGenerator,然后通过String.format("%1$012d", id)来自定义字符串格式,具体代码如下
import java.io.Serializable;@b@import java.util.Properties;@b@@b@import org.hibernate.HibernateException;@b@import org.hibernate.MappingException;@b@import org.hibernate.dialect.Dialect;@b@import org.hibernate.engine.spi.SessionImplementor;@b@import org.hibernate.id.Configurable;@b@import org.hibernate.id.PersistentIdentifierGenerator;@b@import org.hibernate.id.SequenceGenerator;@b@import org.hibernate.type.LongType;@b@import org.hibernate.type.Type;@b@@b@public class StringSequenceGenerator extends SequenceGenerator implements PersistentIdentifierGenerator,Configurable{@b@ @b@ @Override@b@ public void configure(Type type, Properties params, Dialect dialect) throws MappingException {@b@ super.configure(new LongType(), params, dialect);@b@ }@b@ /**@b@ * 将数据库中查询的Sequence转换成为字符串使用@b@ */@b@ public Serializable generate(SessionImplementor session, Object obj) @b@ throws HibernateException {@b@ Serializable sequnece = super.generate(session, obj);@b@ Long id = Long.parseLong(sequnece.toString());@b@ return String.format("%1$012d", id);@b@@b@ }@b@@b@}
2.使用通过Hibernate注释的方式注入使用,如下DataField的Pojo的类主键生成方式
import javax.persistence.Column;@b@import javax.persistence.Entity;@b@import javax.persistence.GeneratedValue;@b@import javax.persistence.Id;@b@import javax.persistence.Table;@b@import org.hibernate.annotations.GenericGenerator;@b@@b@@Entity@b@@Table(name = "TAB_DATA_FIELD")@b@public class DataField {@b@ @b@ private String id; //ID@b@ private String name; //名称 @b@@b@ @Id@b@ @GeneratedValue(generator = "CustomerFieldsGenerator")@b@ @GenericGenerator(name = "CustomerFieldsGenerator", strategy = "com.woopa.common.StringSequenceGenerator")@b@ public String getId(){@b@ return this.id;@b@ }@b@ public void setId(String id){@b@ this.id = id;@b@ }@b@@b@ @Column(name = "NAME")@b@ public String getName(){@b@ return this.name;@b@ }@b@ public void setName(String name){@b@ this.name = name;@b@ }@b@@b@ @b@ @b@ @b@}