复合主键的生成

package com.ly.commons;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class MyKey implements IdentifierGenerator {

	public Serializable generate(SessionImplementor ss, Object arg1)
			throws HibernateException {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
		String str =sdf.format(date);
		
		String sql ="select USERSQL.nextval FROM dual";
		String id="";
		Connection conn =ss.getJDBCContext().getConnectionManager().getConnection();
		try {
			PreparedStatement ps =conn.prepareStatement(sql);
			ResultSet res =ps.executeQuery();
			while(res.next()){
				id=res.getString(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		int size =6-id.length();
		for(int i=0;i<size;i++){
			id="0"+id;
		}
		return Long.parseLong(str+id);
	}
}
//-------------------------------------------------------------------



<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.ly.domain.Users" table="USERS" schema="SCOTT">
        <id name="userid" type="java.lang.Long">
            <column name="USERID" precision="22" scale="0" />
            <generator class="com.ly.commons.MyKey" />
            
        </id>
        <property name="username" type="java.lang.String">
            <column name="USERNAME" length="20" />
        </property>
        <property name="image" type="java.lang.String">
            <column name="IMAGE" />
        </property>
    </class>
</hibernate-mapping>

你可能感兴趣的:(java,sql,Hibernate,.net,MyEclipse)