fabiojose
12/5/2014 - 12:23 PM

Persistence.Custom.Generator.Eclipselink

Persistence.Custom.Generator.Eclipselink

import

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

persistence.xml

<property name="eclipselink.session.customizer" value="com.domain.project.CustomGenerator"/>

usage

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

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

import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.internal.databaseaccess.Accessor;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sessions.Session;

public class CustomGenerator extends Sequence implements SessionCustomizer {
	private static final long serialVersionUID = -909445778257599819L;
	
	private static final Map<Object, AtomicInteger> SEQUENCERS = new Hashtable<Object, AtomicInteger>();
	
	private static Serializable next(final Object object) {
		
		AtomicInteger sequencer = SEQUENCERS.get(object);
		if(null== sequencer) {
			sequencer = new AtomicInteger( (int)System.currentTimeMillis() );
			SEQUENCERS.put(object, sequencer);
		}
		
		return new Integer(sequencer.getAndIncrement());
	}
	
	public CustomGenerator(){
		
	}
	
	public CustomGenerator(String name) {
		super(name);
	}

	@Override
	public void customize(Session session) throws Exception {
		
		Sequence sequence = new CustomGenerator(CustomGenerator.class.getName());
		
		session.getLogin().addSequence(sequence);
		
	}

	@Override
	public Object getGeneratedValue(Accessor accessor, AbstractSession session, String name) {
		return CustomGenerator.next(name);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Vector getGeneratedVector(Accessor arg0, AbstractSession arg1,
			String arg2, int arg3) {
		return null;
	}

	@Override
	public void onConnect() {		
	}

	@Override
	public void onDisconnect() {		
	}

	@Override
	public boolean shouldAcquireValueAfterInsert() {
		return false;
	}

	@Override
	public boolean shouldUseTransaction() {
		return false;
	}
	
	@Override
	public boolean shouldUsePreallocation() {
		return false;
	}

}