您的位置:首页 > 其它

用户自定义ID Generator的例子

2004-07-16 10:10 363 查看
PO
package com.dsii.hibernate.po;
public class Company {
private String id;
private String name;
private String year;
public Company() { }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getYear() { return year; }
public void setYear(String year) { this.year = year; }
}
XML
     uid_table next_hi_value_column C
Customized Id Generator
package com.dsii.hibernate.po;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Properties;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.dialect.Dialect;
import net.sf.hibernate.engine.SessionImplementor;
import net.sf.hibernate.type.Type;
import net.sf.hibernate.util.PropertiesHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.hibernate.id.TableGenerator;
public class CustomizedIdGenerator extends TableGenerator {
private String prefix;
private static final Log log = LogFactory.getLog(CustomizedIdGenerator.class);
public void configure(Type type, Properties params, Dialect d) {
super.configure(type, params, d);
prefix = params.getProperty("prefix") == null ? "Pre" : params.getProperty("prefix");
   }
public synchronized Serializable generate(SessionImplementor session, Object obj) throws SQLException, HibernateException {
Integer integer = (Integer)super.generate(session, obj);
      return prefix+integer; }
   }
Bean
package com.dsii.hibernate.po;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
public class TestCompany {
private static SessionFactory _sessions = null;
static {
try {
Configuration cfg = new Configuration();
cfg.addClass(Company.class);
SchemaExport dbExport = new SchemaExport(cfg);
dbExport.create(true, true);
_sessions = cfg.buildSessionFactory();
      }catch (MappingException e) { 
e.printStackTrace();
      }catch (HibernateException e) { 
e.printStackTrace();
      }
   }
public static void main(String[] args) throws HibernateException {
System.out.println("----------------begin");
Company c1 = new Company();
c1.setName("dsii");
c1.setYear("2004");
Company c2 = new Company();
c2.setName("dsii");
c2.setYear("2004");
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(c1);
session.save(c2);
tx.commit();
   }catch (HibernateException he) {
      if (tx != null) { tx.rollback(); }throw he; 
   }finally { session.close(); }
System.out.println("----------------end");
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: