我尝试使用 UUID 作为我的数据库的 ID,但我根本无法让它工作。
第一次尝试是:
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid4")
private UUID id;
但这会生成一些难看的字节码。所以我添加了一个类型注释:
@Id
@GeneratedValue(generator = "hibernate-uuid")
@GenericGenerator(name = "uuid", strategy = "uuid4")
@Type(type="org.hibernate.type.UUIDCharType")
private UUID id;
有了这个,我在我的 mysql 数据库中得到了一个字符表示,但使用我的存储库查询数据库:
public interface CommentsRepository extends CrudRepository<Comment, UUID> {
Comment findById(final UUID imageId);
}
不会找到任何结果 - 即使存在具有给定 UUID 的条目,它也不会返回结果。 即使我直接在我的数据库上使用纯 SQL,它也不会找到任何结果。
我还需要做些什么来让 UUID 正常工作吗?
编辑
试试这个:
@Data
@Entity
public class Comment implements Serializable {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Type(type = "uuid-char")
private UUID id;
}
并添加一些默认值:
@Component
@Slf4j
public class CommentsSampleData implements CommandLineRunner {
private final CommentsRepository repository;
@Autowired
public CommentsSampleData(final CommentsRepository repository) {
this.repository = repository;
}
@Override
public void run(String... args) {
repository.save(new Comment());
repository.save(new Comment());
repository.save(new Comment());
repository.save(new Comment());
}
}
结果如下表:
表演:
SELECT * FROM comment WHERE id = 'b076a9f7-7e9e-4f5a-91f8-e66c7d076fac'
结果:
这意味着没有结果,但应该有一个。使用 jpa 也不会返回任何内容。
最佳答案
它适用于以下内容:
@Id
@GeneratedValue(generator = "uuid4")
@GenericGenerator(name = "UUID", strategy = "uuid4")
@Type(type = "org.hibernate.type.UUIDCharType")
@Column(columnDefinition = "CHAR(36)")
private UUID id;
关于spring - hibernate :无法通过 UUID 找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63228923/