org.hibernate.type.UUIDCharType 使用 java.util.UUID#toString, fromString 将 UUID 映射到 String 存储为 CHAR or VARCHAR
package org.example.demo.hibernate;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;
import org.hibernate.annotations.Type;
public class Test {
public static void main(String[] args) throws Exception {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
EntityManager em = factory.createEntityManager();
Product product = new Product();
product.no = UUID.randomUUID();
em.getTransaction().begin();
em.persist(product);
em.getTransaction().commit();
em.clear();
Product p = em.find(Product.class, product.id);
// fdba8bcc-6733-4341-a366-60a0728e01f7
System.out.println(p.no);
em.close();
factory.close();
}
@Entity(name = "Product")
public static class Product {
@Id
@GeneratedValue
Integer id;
@Type(type = "uuid-char")
UUID no;
}
}
生成 SQL
drop table if exists Product cascade
drop sequence if exists hibernate_sequence
create sequence hibernate_sequence start 1 increment 1
create table Product (id int4 not null, no varchar(255), primary key (id))
select nextval ('hibernate_sequence')
insert into Product (no, id) values ('fdba8bcc-6733-4341-a366-60a0728e01f7', 1)
select test_produ0_.id as id1_0_0_, test_produ0_.no as no2_0_0_ from Product test_produ0_ where test_produ0_.id=1