java idgenerator_转:用户自定义ID Generator的例子(JavaJason)

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");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值