首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Hibernate 自定义主键生成种

2012-09-02 
Hibernate 自定义主键生成类KeyGen类用于生成 形如 yyyyMMDD+序号形式的主键package keyGenpublic class

Hibernate 自定义主键生成类
KeyGen类
用于生成 形如 yyyyMMDD+序号形式的主键



package keyGen;public class OrderKeyGen implements IdentifierGenerator {private static SimpleDateFormat preFix = new SimpleDateFormat("yyyyMMdd");@Overridepublic synchronized Serializable generate(SessionImplementor arg0,Object arg1) throws HibernateException {String datePart = preFix.format(new Date());String idString = datePart + System.currentTimeMillis() % 99;return idString;}}


POJO类定义
package db;@Entity@Table(name = "t_diykey", catalog = "test")public class TDiykey implements java.io.Serializable {// Fieldsprivate String dbid;private String notes;// Constructors/** default constructor */public TDiykey() {}/** full constructor */public TDiykey(String notes) {this.notes = notes;}// Property accessors@GenericGenerator(name = "generator", strategy = "keyGen.OrderKeyGen")@Id@GeneratedValue(generator = "generator")@Column(name = "dbid", unique = true, nullable = false, length = 10)public String getDbid() {return this.dbid;}public void setDbid(String dbid) {this.dbid = dbid;}@Column(name = "notes", length = 20)public String getNotes() {return this.notes;}public void setNotes(String notes) {this.notes = notes;}}


测试类
public class MyDIYKeyTest {    public static void main(String[] args) {Session session = HibernateSessionFactory.getSession();Transaction tx = session.beginTransaction();TDiykey tDiykey = new TDiykey();tDiykey.setNotes("aaaa");session.save(tDiykey);tx.commit();HibernateSessionFactory.closeSession();}

热点排行