如何在Java Hibernate中将id设置为String?

时间:2019-08-19 23:26:52

标签: java hibernate

我有以下代码:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import java.io.Serializable;

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue
    private final String id = null; // there's Long data type originally

    @Version
    private Long version;

}

如果我运行它,我会得到:

Caused by: org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String

如果我删除@GeneratedValue注释,我仍然会得到:

Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

问题是我的对象可能在id字段下包含字符串值,因此我想将Long更改为String

1 个答案:

答案 0 :(得分:0)

我应该使用以下2行:

@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")

代替

@GeneratedValue