Created
January 2, 2018 14:04
-
-
Save kenji-getpowered/0812990a5ff0e05873fbc867077ea82d to your computer and use it in GitHub Desktop.
Hibernate UUID keeper for import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.mikaelkrok.hibernate; | |
import java.io.Serializable; | |
import java.util.Properties; | |
import org.hibernate.engine.spi.SessionImplementor; | |
import org.hibernate.id.UUIDGenerator; | |
import org.hibernate.service.ServiceRegistry; | |
import org.hibernate.type.Type; | |
/** | |
* Allows to keep UUID while new objects are passed. Based on | |
* http://stackoverflow.com/a/5392349/566434. | |
* Used with | |
* <pre> | |
* @Id | |
* @Getter | |
* @Setter | |
* @GeneratedValue(generator = UUIDKeeperGenerator.GENERATOR_STRATEGY) | |
* @GenericGenerator(name = UUIDKeeperGenerator.GENERATOR_STRATEGY, strategy = UUIDKeeperGenerator.GENERATOR_CLASS_NAME) | |
* private String id; | |
* | |
* </pre> | |
*/ | |
public class UUIDKeeperGenerator extends UUIDGenerator { | |
/** | |
* Generator strategy. | |
*/ | |
public static final String GENERATOR_STRATEGY = "uuid-keeper"; | |
/** | |
* Generator class name. | |
*/ | |
public static final String GENERATOR_CLASS_NAME = "com.cegedim.next.servicedirectory.core.model.UUIDKeeperGenerator"; | |
private String entityName; | |
@Override | |
public void configure(final Type type, final Properties params, final ServiceRegistry serviceRegistry) { | |
this.entityName = params.getProperty(ENTITY_NAME); | |
super.configure(type, params, serviceRegistry); | |
} | |
@Override | |
public Serializable generate(final SessionImplementor session, final Object object) { | |
Serializable id = session.getEntityPersister(this.entityName, object).getIdentifier(object, session); | |
if (id == null) { | |
return super.generate(session, object); | |
} | |
else { | |
return id; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment