Hibernate之自定义ID生成器

本文介绍了一种基于当前日期和随机数的自定义ID生成器实现方法,并使用了Apache Commons Lang库中的RandomStringUtils来生成随机数部分。该生成器适用于需要唯一标识符的场景。
一 xxx.hml.xml

<id name="id" type="java.lang.String">
<column name="id" length="22" />
<generator class="xx.xx.IdentifierGeneratorImpl" />
</id>

二 具体实现: IdentifierGeneratorImpl.java
用到了commons工具包中的RandomStringUtils :o

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang.RandomStringUtils;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

public class IdentifierGeneratorImpl implements IdentifierGenerator, Configurable {

private static final int IDLENG = 32;
private static final String YYMMDDHHMMSS = "yyyyMMddhhmmss";

private static String getCurrentDate(){
return new SimpleDateFormat(YYMMDDHHMMSS).format(new Date());
}

public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
return new StringBuilder().append(getCurrentDate()).append("-").append(RandomStringUtils.randomNumeric(IDLENG));
}

public void configure(Type type, Properties params, Dialect d) throws MappingException {

}
public static void main(String[] args) {
IdentifierGeneratorImpl pu = new IdentifierGeneratorImpl();
System.out.println(pu.generate(null, null));
/*int random = 32;
System.out.println(RandomStringUtils.randomNumeric(random));
System.out.println(RandomStringUtils.randomAscii(random));
System.out.println(RandomStringUtils.randomAlphabetic(random));
System.out.println(RandomStringUtils.randomAlphanumeric(random));*/

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值