首页 > 学院 > 开发设计 > 正文

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

2019-11-08 01:23:17
字体:
来源:转载
供稿:网友

1、继承IdentifierGenerator,Configurable 这2个接口

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"); }}

2、

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@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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表