如何从Hibernate获取自定义类型的数据库方言?

时间:2015-01-03 02:10:04

标签: java spring hibernate spring-boot

所以我写了这个,但是它打破了Spring Boot 1.2.0,不知道为什么它与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;
    }

}

打破looks like it might have something to do with attempting to get the nonexistant properties file

我如何从Hibernate或Spring获得方言?

1 个答案:

答案 0 :(得分:0)

看起来你非常依赖Spring Boot的内部实现。它可能有效,但它可能会在版本之间发生变化,这会使你的应用程序变得脆弱。

我无法想到很好的解决方案,但在Retrieve auto-detected hibernate dialect中建议使用更好的解决方案,即获取对SessionFactory的引用,将其转换为{{ 1}},然后在其上调用SessionFactoryImplementor。它仍然不是一个好的解决方案,因为在某些未来版本的Hibernate中,演员阵容也会停止工作,但这种可能性不大。