Hibernate UUID with PostgreSQL and SQL Server

前端 未结 2 431
日久生厌
日久生厌 2020-12-07 02:28

I have an application I would like to run on both PostgreSQL and SQL Server. I would like to use java.util.UUID as the IDs.

I have defined my columns in SQL Server a

2条回答
  •  甜味超标
    2020-12-07 03:09

    I ended up writing my own Dialect and BasicType that links the Java type java.util.UUID to uuid-char by default.

    This class is inspired by the PostgreSQLDialect

    public class MySQLServerDialect extends SQLServer2012Dialect {
    
        public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
            super.contributeTypes( typeContributions, serviceRegistry );
    
            typeContributions.contributeType( SQLServerUUIDType.INSTANCE );
        }
    }
    

    This class is inspired by the UUIDCharType

    public class SQLServerUUIDType extends AbstractSingleColumnStandardBasicType implements LiteralType {
        public static final SQLServerUUIDType INSTANCE = new SQLServerUUIDType();
    
        public SQLServerUUIDType() {
            super( VarcharTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE );
        }
    
        @Override
        protected boolean registerUnderJavaType() {
            return true;
        }
    
        public String getName() {
            return "my-uuid";
        }
    
        public String objectToSQLString(UUID value, Dialect dialect) throws Exception {
            return StringType.INSTANCE.objectToSQLString( value.toString(), dialect );
        }
    }
    

    I don't think it's the most elegant solution, but it works for now.

提交回复
热议问题