All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.loom.addons.id.SpringIdGeneratorService Maven / Gradle / Ivy

The newest version!
package org.loom.addons.id;

import javax.inject.Singleton;
import javax.persistence.PersistenceContext;

import org.loom.persistence.ExtendedEntityManager;
import org.loom.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;

@Singleton 
public class SpringIdGeneratorService implements IdGeneratorService {

	@PersistenceContext
	private ExtendedEntityManager entityManager;
	
	@Transactional
	public String generateId(Class persistentClass, String idFieldName, String keyText) {
		// get an id
		String candidateId = StringUtils.generateIdentifier(keyText);
		
		// guarantee uniqueness
		// using LIKE would yield worse performance and is not GAE-compliant
		Number n = (Number)entityManager.findSingle("select count(o) from " + persistentClass.getName() + " o where o." + idFieldName + " >= ?1 and o." + idFieldName + " < ?2", 
				candidateId,  candidateId + '\ufffd');
		if (n.intValue() > 0) {
			candidateId = candidateId + "-" + n;
		}
		return candidateId;
	}
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy