org.hibernate.type.UUIDBinaryType 使用 java.util.UUID#getMostSignificantBits, getLeastSignificantBits 将 UUID 映射到 byte[] 存储为 BINARY

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);
        // cc522942-cdeb-4929-90ef-a337292feb04
        System.out.println(p.no);

        em.close();
        factory.close();
    }

    @Entity(name = "Product")
    public static class Product {
        @Id
        @GeneratedValue
        Integer id;
        @Type(type = "uuid-binary")
        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 bytea, primary key (id))
select nextval ('hibernate_sequence')
insert into Product (no, id) values ('CC522942CDEB492990EFA337292FEB04', 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

results matching ""

    No results matching ""