我可以在Hibernate创建自己的序列,就像我有一个数据库序列一样,我必须在序列之前添加2个字符吗?
答案 0 :(得分:3)
您可以创建自己的标识符生成器。看看这个blog post,它基本上展示了如何做一些类似于你正在寻找的东西(除非我误解了这个问题):
用于Id字段的自定义Hibernate序列生成器
我有一张带有主键的表格 格式M001,M002等(不允许 想想M999之后会发生什么 目前)。我正在使用Hibernate 注释,我找到了一个很好的方法 生成主键值 对于新记录:
首先我创建了一个数据库序列 使用。然后我实施了
org.hibernate.id.IdentifierGenerator
;public class StockCodeGenerator implements IdentifierGenerator { private static Logger log = Logger.getLogger(StockCodeGenerator.class); public Serializable generate(SessionImplementor session, Object object) throws HibernateException { String prefix = "M"; Connection connection = session.connection(); try { PreparedStatement ps = connection .prepareStatement("SELECT nextval ('seq_stock_code') as nextval"); ResultSet rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt("nextval"); String code = prefix + StringUtils.leftPad("" + id,3, '0'); log.debug("Generated Stock Code: " + code); return code; } } catch (SQLException e) { log.error(e); throw new HibernateException( "Unable to generate Stock Code Sequence"); } return null; } }
然后,在我的实体课中,我只是 像这样注释id字段:
@Id @GenericGenerator(name="seq_id", strategy="my.package.StockCodeGenerator") @GeneratedValue(generator="seq_id") @Column(name = "stock_code", unique = true, nullable = false, length = 20) public String getStockCode() { return this.stockCode; }
答案 1 :(得分:0)
试试这个。使用日期和日历
public class StockCodeGenerator
implements IdentifierGenerator
{
private static Logger log = Logger.getLogger(StockCodeGenerator.class);
public StockCodeGenerator() {}
public int generateCustId()
{
Random random = new Random();
return random.nextInt(100);
}
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException
{
String prefix = "Custom_String";
Connection connection = session.connection();
System.out.println(session.connection());
Date date = new Date();
Calendar calendar = Calendar.getInstance();
return prefix + "_" + generateCustId() + "_" + calendar.get(1);
}
}
然后在@GenericGenerator注释中使用它
@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")