思路:
主键为日期年月日自增加型.如当前主键为20071016000001.那下一条主键为20071016000002.
问题:
第一次session.save(object)的时候生成主键对了的.
但是第二次session.save(object)的时候就不对了.返回的主键为0
因为里面的private String sql为空.
原因是可能没有执行void configure()方法.请问各位大大:我错在那里?或者各位给我一个写好的主键生成品吧.
拜谢!!public class PrimaryKeyGenerator implements IdentifierGenerator,Configurable{
 private String sql=null;
    
    public synchronized Serializable generate(SessionImplementor session, Object object)
    throws HibernateException{
     Long next=new Long(0);
        if (sql!=null){
         try{
         next=new Long(getNext( session.connection()));
         }catch(SQLException e){
         e.printStackTrace();
         }
        }
       return next;
    }     public void configure(Type type, Properties params, Dialect d)
        throws MappingException {
     java.util.Date dt = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date;
date = sdf.format(dt) ;
        String table = params.getProperty("table"); //表名
        if (table==null) table = params.getProperty(PersistentIdentifierGenerator.TABLE);
        String column = params.getProperty("column");
        if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK); //字段名
        String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
        sql ="select max(" + column + ") from "+( schema==null ? table : schema + '.' + table )+" where  left("+column+",8)='"+date+"'" ;
    }     private long getNext(Connection conn) throws SQLException {
        PreparedStatement st = conn.prepareStatement(sql);
        ResultSet rs = null;
        long id;
        try {
           rs = st.executeQuery();
           rs.last();
           Object obj=rs.getObject(1);
           //rs!=null
            if(obj==null){
             //如果今天是第一条记录
             java.util.Date dt = new java.util.Date();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
     String date;
     date = sdf.format(dt) ;
             date=date+"000001";
             id=Long.parseLong(date);
             return id;
            }else{
             id=rs.getLong(1)+1;
            return id;
            }
        }finally{
         sql=null;
            if (rs!=null) rs.close();
            st.close();
        }
    }}