fabiojose
12/4/2014 - 6:49 PM

Persistence.Custom.Generator.Hibernate

Persistence.Custom.Generator.Hibernate

import

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;

usage

@Id
@GenericGenerator(name="GEN_ID", strategy = "com.domain.project.CustomGenerator")
@GeneratedValue(generator = "GEN_ID", strategy = GenerationType.AUTO)
@Column(name = "entity_id", length = 10, nullable = false)
private Integer id;
package com.domain.project;

import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

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

public class CustomGenerator implements IdentifierGenerator {
	
	private static final Map<Class<?>, AtomicInteger> SEQUENCERS = new Hashtable<Class<?>, AtomicInteger>();
	
	private static Serializable next(final Object object) {
		
		AtomicInteger sequencer = SEQUENCERS.get(object.getClass());
		if(null== sequencer) {
			sequencer = new AtomicInteger( (int)System.currentTimeMillis() );
			SEQUENCERS.put(object.getClass(), sequencer);
		}
		
		return new Integer(sequencer.getAndIncrement());
	}

	@Override
	public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
		
		return CustomGenerator.next(object);
		
	}

}