主键格式:
TID001
TID002
TID003
TID004
查了一下hibernate的主键策略 貌似没有可以这样的
请问 这个只能自己去控制吗,每次生成的ID的时候 去数据库里查一把?
解决方法:继承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");
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。