Posted on 2008-09-02 12:51
Neil's NoteBook 阅读(812)
评论(0) 编辑 收藏
最近项目中使用到的一个主键自动生成策略,持久层框架为Hibernate,数据库为Oracle9i.
生成方式是:当天时间(8位)+流水号(8位),以下是代码
1 import java.io.Serializable;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4 import java.util.Properties;
5
6 import org.hibernate.HibernateException;
7 import org.hibernate.dialect.Dialect;
8 import org.hibernate.engine.SessionImplementor;
9 import org.hibernate.id.TableGenerator;
10 import org.hibernate.type.Type;
11
12 import com.seektax.tams.util.StringUtil;
13
14 public class MyCustomizedIdGenerator extends TableGenerator {
15 private String rulesize;
16 private String curDate;
17
18 public void configure(Type type, Properties params, Dialect d) {
19 super.configure(type, params, d);
20 curDate = params.getProperty("curDate") == null ? "dddddddd" : getCurDate();
21 rulesize = params.getProperty("rulesize") == null ? "0" :
22 params.getProperty("rulesize");
23 }
24
25 public synchronized Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
26 StringBuffer Iddm = new StringBuffer(512);
27 String tempid = String.valueOf(super.generate(session, obj));
28 tempid = StringUtil.LPAD(tempid, Integer.valueOf(rulesize).intValue(), "0");
29 if(tempid.length() > Integer.parseInt(rulesize))
30 {
31 tempid = tempid.substring(tempid.length()-Integer.parseInt(rulesize), tempid.length());
32 }
33 Iddm.append(curDate);
34 Iddm.append(tempid);
35 return new Long(Long.parseLong((Iddm.toString())));
36 }
37
38 /**
39 * 获取当天日期
40 */
41 private String getCurDate()
42 {
43 Date curDate = new Date();
44 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
45 String curDay = sdf.format(curDate);
46 return curDay;
47 }
48
49 }
50
String tempid = String.valueOf(super.generate(session, obj));
tempid = StringUtil.LPAD(tempid, Integer.valueOf(rulesize).intValue(), "0");
以上两句话是当自动生成的ID位数不够时自动补零.方法代码为:
1 /**
2 * 类似于oralce LPAD 从左到右
3 * @param source
4 * @param newSize
5 * @param replaceString
6 * @return
7 */
8 public static String LPAD(String source, int newSize, String replaceString) {
9 String result = "";
10 if (source.length() < newSize) {
11 for (int i = 0; i < newSize - source.length(); i++) {
12 result += replaceString;
13 }
14 result = result + source;
15
16 } else {
17 result = source;
18 }
19 return result;
20 }
然后,需要在配置文件中配置该主键生成策略,代码如下:
1 <id name="id" type="long">
2 <column name="ID" precision="16" scale="0" />
3 <generator class="com.seektax.tams.modules.xxcj.MyCustomizedIdGenerator">
4 <param name="table">SERIAL_NO</param> //数据库表名
5 <param name="column">DAJBXXID</param> //表中字段名
6 <param name="curDate">curDate</param>
7 <param name="rulesize">8</param> //定义位数
8 </generator>
9 </id>
配置好这些就OK了!
注:由于项目中使用的是双主键,在插入一方的同时,多方也要重新获得主键,如:
1 DaPageId id = new DaPageId();
2 id.setXh(i+1);
3 id.setDaId(jbxx.getId());
(完)