gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:33:08 25 4
gpt4 key购买 nike

我有一个实体,它使用 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:引用这个问题:

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;

关于java - Hibernate:是否可以修改生成的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35792291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com