用户自定义ID Generator的例子(http://www.hibernate.org.cn/viewtopic.php?t=6281&highlight=IdentifierGenerator)

  用户自定义ID Generator的例子

今天终于有了点时间再整理点ID Generator的东东,算是对本论坛的回报

简单版:
http://www.hibernate.org.cn/89.html

进阶版:
PO
java代码: 

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
java代码: 

<?xml version=" 1. 0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http: //hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
   < class name="com. dsii. hibernate. po. Company" table="company" >
      <id name="id" column="id"  length=" 12">
         <generator class="com. dsii. hibernate. po. CustomizedIdGenerator">
              <param name="table">serial_no_temp</param>
              <param name="field_column_name">fieldName</param>
              <param name="value_column_name">nextIntNo</param>
              <param name="field_name">companyNo</param>
              <param name="rule">*yyyyMMdd,-,#3</param>
        </generator>
      </id>
     
      <property name="name" column="name" length=" 30" />
      <property name="year" column="year" length=" 4" />
   </ class>
</hibernate-mapping>


说明:在使用之前应在数据库中建立serial_no_temp表,并在表中加入数据fieldName列值为companyNo

 資料表名稱 serial_no_temp 說明 流水號暫存檔
欄位名稱    資料型態   長度   欄位說明
fieldName   varchar   30   流水號欄位名稱
nextIntNo    int      4    整數流水號
nextStringNo  varchar   30   字串标记
description   text          說明  

資料表名稱 company 說明 员工表
欄位名稱   資料型態   長度   欄位說明
id      varchar   12     流水號
name    varchar   20    员工名
year     varchar   4     随便加的
主鍵策略   新增策略: 系統自動產生id,編碼原則: yyyyMMdd+”-”+3碼流水號
修改策略: 不可修改
刪除策略:
備註

 Generator:
[code:1:dd7bc65a41]package com.dsii.common.po;

import java.io.*;
import java.sql.*;
import java.util.*;

import net.sf.hibernate.*;
import net.sf.hibernate.dialect.*;
import net.sf.hibernate.engine.*;
import net.sf.hibernate.id.*;
import net.sf.hibernate.type.*;
import net.sf.hibernate.util.*;
import org.apache.commons.logging.*;

public class CustomizedIdGenerator
implements PersistentIdentifierGenerator, Configurable {

/**
* The table parameter
*/
public static final String TABLE = "table";

/**
* The value parameter
*/
public static final String VALUE_COLUMN_NAME = "value_column_name";

/**
* The field parameter
*/
public static final String FIELD_COLUMN_NAME = "field_column_name";

/**
* The temp parameter
*/
public static final String TEMP_COLUMN_NAME = "temp_column_name";

/**
* The Field Name parameter
*/
public static final String FIELD_NAME = "field_name";

/**
* The role parameter
*/
public static final String RULE = "rule";

private static final Log log = LogFactory.getLog(TableGenerator.class);

private String tableName;
private String field_column_name;
private String value_column_name;
private String temp_column_name;
private String field_name;
private String rule;
private String query;
private String update;
private String tempStringValue;
private String newTempStringValue;

/**
*
* <p><code>configure</code></p>
* @param type
* @param params
* @param dialect
* @author:Jason 2004-3-8
* @since:1.0
*/
public void configure(Type type, Properties params, Dialect dialect) {
this.tableName =
PropertiesHelper.getString(TABLE, params, "serial_no_temp");
this.field_column_name =
PropertiesHelper.getString(FIELD_COLUMN_NAME, params, "fieldName");
this.value_column_name =
PropertiesHelper.getString(VALUE_COLUMN_NAME, params, "nextIntNo");
this.temp_column_name =
PropertiesHelper.getString(
TEMP_COLUMN_NAME,
params,
"nextStringNo");
this.field_name =
PropertiesHelper.getString(FIELD_NAME, params, "field_name_record");
this.rule = PropertiesHelper.getString(RULE, params, "#4#");

String schemaName = params.getProperty(SCHEMA);
if (schemaName != null && tableName.indexOf(StringHelper.DOT) < 0) {
tableName = schemaName + '.' + tableName;
}
query =
"select "
+ value_column_name
+ ","
+ temp_column_name
+ " from "
+ tableName
+ " where "
+ field_column_name
+ " = '"
+ field_name
+ "'";
if (dialect.supportsForUpdate()) {
query += " for update";
}
}

/**
*
* <p><code>generate</code></p>
* @param session
* @param object
* @return
* @throws SQLException
* @throws HibernateException
* @author:Jason 2004-3-8
* @since:1.0
*/
public synchronized Serializable generate(
SessionImplementor session,
Object object)
throws SQLException, HibernateException {
Connection conn = session.getBatcher().openConnection();
Serializable result;
int nextNo;

try {
PreparedStatement qps = conn.prepareStatement(query);
try {
ResultSet rs = qps.executeQuery();
if (!rs.next()) {
String err =
"系統表'" + tableName + "'中

 Bean

java代码: 

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

Hibernate主键产生规则说明

事由:
由于项目中主键产生规则的特殊要求,故扩展了Hibernate的主键产生方法。

使用方法:
*.hbm.xml中配置如下:
   <id name="id" column="id" length="10">
<generator class="com.dsii.common.po.CustomizedIdGenerator">
<param name="table">serial_no_temp</param>
<param name="field_column_name">fieldName</param>
<param name="value_column_name">nextIntNo</param>
<param name="field_name">companyNo</param>
<param name="rule">*yyyyMMdd,-,#3</param>
</generator>
</id>

前置条件:
l 参数table所指定的table要存在。
l 参数table所指定的table中要有参数field_column_name和参数field_column_name所指定的列。
l 参数table所指定的table中要有field_name所指定的记录,并有初始值。
l 参数rule所指定規则应符合“规则说明”的要求。

规则说明
l Rule字串中没有空格。
l 组合元素以半角逗号分隔。
l 日期以半角星号开始,加上时间格式,如:”*yyyyMMdd”。
l 数字以井号开始,加上数字位数。如:”#4”。
  
  例:结果格式  20040610-0004 rule格式:*yyyyMMdd,-,#4
    结果格式  R001 rule格式:R,#3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值