hibernate 3 ID策略生成器自定义,可用于注释 - 规则: 九位业务编号 + 六位日期 + 六位自增长序列 ...

/**
*hibernate ID策略生成器 自定义 - 规则: 业务编号 + 日期 + 六位自增长序列
*/
public class MyKeyGenerator implements IdentifierGenerator, Configurable {

private static final Log log = LogFactory.getLog(MyKeyGenerator.class);

private long next;

private String sql;
private String table;
private String column;
private String schema;


public synchronized Serializable generate(SessionImplementor session,
Object object) throws HibernateException {
SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
String preDate = f.format(new Date());
LogAction logaction = new LogAction();
// String bh = logaction.getBh();
String bh = "123456789";
return bh + preDate + getNext(session, bh,table);

}

public void configure(org.hibernate.type.Type type, Properties params,
Dialect d) throws MappingException {
table = params.getProperty("table");
if (table == null)
table = params.getProperty(PersistentIdentifierGenerator.TABLE);
column = params.getProperty("column");
if (column == null)
column = params.getProperty(PersistentIdentifierGenerator.PK);
schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);

}
/**
* 得到当前表ID的最后六位的最大数
*
* @param session
* @param jsbh
* @return
*/
private String getNext(SessionImplementor session, String bh,String table) {
sql = "select max(substr("+column+",16)) from "+(schema == null ? table : schema + '.' + table)+" where substr("+column+",10,6) = to_char(sysdate,'yyMMdd') and substr("+column+",0,9) = '" + bh + "' and length("+column+")=21 ";
log.info("fetching initial value: " + sql);

try {
PreparedStatement st = session
.getBatcher()
.prepareSelectStatement(
sql);
try {
ResultSet rs = st.executeQuery();
try {
if (rs.next()) {
next = rs.getLong(1) + 1;
if (rs.wasNull())
next = 1;
} else {
next = 1;
}
sql = null;
log.debug("first free id: " + next);
} finally {
rs.close();
}
} finally {
session.getBatcher().closeStatement(st);
}
return toString(6, next);
} catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(session.getFactory()
.getSQLExceptionConverter(), sqle,
"could not fetch initial value for increment generator",
sql);
}
}

/**
* 格式化数字不足补齐
*
* @param num
* @param value
* @return
*/
public static String toString(int num, long value) {
String result = (new Long(value)).toString();
while (num > result.length()) {
result = "0" + result;
}
return result;
}



JAVA中注解使用方法:



@Id @GeneratedValue(generator="custom-id")
@GenericGenerator(name="custom-id", strategy = "javacommon.base.AwdKeyGenerator")
@Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = true, length = 21)
public java.lang.String getId() {
return this.id;
}

0 0 0
(请您对文章做出评价)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值