Hibernate:是否可以修改生成的值?

时间:2016-03-04 09:25:46

标签: java hibernate

我有一个实体,使用uuid作为PRIMARY KEY并生成

@Id
@Column(name = "uuid")
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private UUID uuid;

如何告诉Hibernate使用显式值,还是可以修改Hibernate生成的值?

编辑:我的问题是,在大多数情况下,生成值很好但在某些情况下,我想创建一个带有显式uuid的实体。

我的解决方法(以下由Dipali Vasani建议)

@Id
@Column(name = "uuid")
private UUID uuid;
/**
 * if defined, this will be used instead of the generated one
 */
private transient UUID preferredUuid;

@PrePersist
private void initializeUuid() {
    if (preferredUuid != null) {
        uuid = preferredUuid;
    }
    else {
        uuid = UUID.randomUUID();
    }
}

1 个答案:

答案 0 :(得分:1)

选项1: 提到这个问题:

Does JPA have something like hibernates '@GenericGenerator' for generating custom ids?

和答案:

https://stackoverflow.com/a/7462096/1982680

他们使用了@PrePersist

您可以像:

一样使用它
  @PrePersist
  public void ensureUuid() {
    uuid= ...
  }

选项2: 创建自定义序列

import java.util.UUID;
import java.util.Vector;

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 UUIDSequence extends Sequence implements SessionCustomizer {

    public UUIDSequence() {
        super();
    }

    public UUIDSequence(String name) {
        super(name);
    }

    @Override
    public Object getGeneratedValue(Accessor accessor,
            AbstractSession writeSession, String seqName) {
        return UUID.randomUUID().toString().toUpperCase();
    }

    @Override
    public Vector getGeneratedVector(Accessor accessor,
            AbstractSession writeSession, String seqName, int size) {
        return null;
    }

    @Override
    protected void onConnect() {
    }

    @Override
    protected void onDisconnect() {
    }

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

    @Override
    public boolean shouldOverrideExistingValue(String seqName,
            Object existingValue) {
        return ((String) existingValue).isEmpty();
    }

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

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

    public void customize(Session session) throws Exception {
        UUIDSequence sequence = new UUIDSequence("system-uuid");

        session.getLogin().addSequence(sequence);
    }

}

注册序列

自定义程序可以在API中指定为持久性单元属性:

properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
                "eclipselink.example.UUIDSequence");

或XML格式:

<property name="eclipselink.session.customizer" value="eclipselink.example.UUIDSequence"/>

使用序列

@Id
@GeneratedValue(generator="system-uuid")
@Column(name="uuid")
private UUID uuid;