JPA Global Sequence provider EJB Singleton


package com.origami.censocat.service;

import java.util.concurrent.atomic.AtomicLong;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * @author Fernando
 */
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Lock(LockType.WRITE)
public class GlobalSequenceProvider implements GlobalSequenceProviderLocal {
    
    @PersistenceContext(unitName = "CensoCat_PU")
    private EntityManager em;
    
    private Long actualId;
    private Long limitId;
    private final Long interval = 20L;

    public GlobalSequenceProvider() {
    }
    
    protected Boolean esDisponible(){
        if(actualId==null || actualId>=limitId){
            return false;
        }
        return true;
    }
    
    @Override
    public Long getNextId(){
        if(!this.esDisponible()){
            // obtener nuevo intervalo de secuencia
            genNextInterval();
        }
        actualId++;
        return actualId;
    }
    
    protected void genNextInterval(){
        Query q = em.createNativeQuery("select nextval('global_seq')");
        actualId = (Long)q.getSingleResult();
        limitId = actualId + interval;
    }
    
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s