如何生成 字符+数字的自增主键 hibernate+oracle

 我来答
逆心小土豆
2017-08-26 · TA获得超过3618个赞
知道大有可为答主
回答量:2500
采纳率:0%
帮助的人:729万
展开全部
解渗磨决方法:继承IdentifierGenerator,Configurable 这2个接口

package com.testplatform.idGenerator;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
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 IDGenerator implements IdentifierGenerator,Configurable {

private String prefix;
private String seq;
static Logger log4j = Logger.getLogger(IDGenerator.class.getClass());
public Serializable generate(SessionImplementor session, Object arg1)
throws HibernateException {
// TODO Auto-generated method stub

Connection connection = session.connection();
try {
//SELECT seq_date_info_id.nextval from dual;
PreparedStatement ps = connection
.prepareStatement("SELECT "+seq+".nextval from dual");

ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("nextval"派亩);
String code = prefix+id;
//丛羡斗String code = prefix + StringUtils.leftPad("" + id,3, '0');
log4j.warn("IDGenerator: " + code);
return code;
}

} catch (SQLException e) {
log4j.warn(e);
throw new HibernateException(
"Unable to generate id ");
}
return null;
}
public void configure(Type arg0, Properties params, Dialect arg2)
throws MappingException {
// TODO Auto-generated method stub
// System.out.println("configure");
/* table = params.getProperty("table");
if (table == null)
table = params.getProperty(PersistentIdentifierGenerator.TABLE);*/
seq = params.getProperty("seq");
prefix = params.getProperty("prefix");
}

}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式