生成器类
package jet.framework.hibernate;
import com.youyang.ui.helper.Constants;
import jet.framework.util.DateUtils;
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.id.PersistentIdentifierGenerator;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Pattern;
public class RefundIDGenerator implements IdentifierGenerator, Configurable {
private static final Logger logger = Logger.getLogger(RefundIDGenerator.class);
private String next;
private String sql;
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
if (sql != null) {
return getNext(session.connection());
} else {
return next;
}
}
public void configure(Type type, Properties params, Dialect d) throws MappingException {
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);
}
private String getNext(Connection conn) throws HibernateException {
try {
PreparedStatement st = conn.prepareStatement(sql);
ResultSet rs = st.executeQuery();
Long maxId = 0l;
StringBuffer tempId = new StringBuffer(Constants.REFUND_KEY);
if (rs.next()) {
next = rs.getString(1);
Pattern pattern = Pattern.compile("^//d*$");
if (pattern.matcher(next.substring(next.length() - 4)).matches()) {
maxId = Long.valueOf(next.substring(next.length() - 4));
}
}
maxId++;
tempId.append(DateUtils.format(new Date(), "yyMM"));
tempId.append(resetId(maxId.toString(), Constants.REFUND_KEY_NUM, "0"));
return tempId.toString();
} catch (SQLException e) {
throw new HibernateException(e);
} finally {
try {
conn.close();
} catch (SQLException e) {
throw new HibernateException(e);
}
}
}
public static String resetId(String source, int newSize, String replaceString) {
String result = "";
if (source.length() < newSize) {
for (int i = 0; i < newSize - source.length(); i++) {
result += replaceString;
}
result = result + source;
} else {
result = source;
}
return result;
}
}
id配置
@Id
@GeneratedValue(generator = "refundIDGenerator")
@GenericGenerator(name = "refundIDGenerator",
strategy = "jet.framework.hibernate.RefundIDGenerator")
@Column(name = "product_order_refund_id")
private String productOrderRefundId;