xenoterracide
xenoterracide

Reputation: 16837

How can I get the database dialect from Hibernate for a Custom Type?

so I had written this but it broke with Spring Boot 1.2.0, not sure why it worked (or appeared to) with 1.1.9

package com.xenoterracide.rpf.infrastructure.db;

import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.PostgresUUIDType;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.type.descriptor.java.UUIDTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

public class UUIDCustomType extends AbstractSingleColumnStandardBasicType {
    public static final String UUID = "uuid-custom";
    private static final Logger log = LoggerFactory.getLogger( UUIDCustomType.class );

    private static final long serialVersionUID = 902830399800029445L;

    private static final SqlTypeDescriptor  SQL_DESCRIPTOR;
    private static final JavaTypeDescriptor TYPE_DESCRIPTOR;

    static {
        Properties properties = new Properties();
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            properties.load( loader.getResourceAsStream( "database.properties" ) );
        }
        catch ( IOException e ) {
            throw new RuntimeException( "Could not load properties!", e );
        }

        String dialect = properties.getProperty( "dialect" );
        SQL_DESCRIPTOR
                = dialect.equals( "org.hibernate.dialect.PostgreSQLDialect" )
                  ? PostgresUUIDType.PostgresUUIDSqlTypeDescriptor.INSTANCE
                  : VarcharTypeDescriptor.INSTANCE;

        log.debug( "dialect {}", dialect );

        TYPE_DESCRIPTOR = UUIDTypeDescriptor.INSTANCE;
    }

    public UUIDCustomType() {
        super(SQL_DESCRIPTOR, TYPE_DESCRIPTOR);
    }

    @Override
    public String getName() {
        return UUID;
    }

}

The breaking looks like it might have something to do with attempting to get the nonexistant properties file.

How could I get the dialect from Hibernate or Spring?

Upvotes: 3

Views: 2668

Answers (1)

skaffman
skaffman

Reputation: 403461

That very much looks like you were relying on the internal implementation of Spring Boot's packaging. it may work, but it's liable to change between versions, which makes your app fragile.

I can't think of good solution off the top of my head, but a better one is suggested in Retrieve auto-detected hibernate dialect, i.e. get a reference to the SessionFactory, cast it to SessionFactoryImplementor, then call getDialect on that. It's still not a good solution since it's also possible that at some future version of Hibernate that cast will cease to work, but that's rather less likely.

Upvotes: 1

Related Questions