Hibernate, Postgres & Array Type

2022-09-03 18:17:46

我卡在一个特定的问题上,使用postgresql 9.3中的数组类型映射到休眠4.1.0。这种类型使我能够拥有非常强大的数据模型,而无需构建大量表和联接。

为了映射使用此特定类型存储的字段,我使用了UserType。

无论如何,它适用于纯休眠(hql),但我还需要将sql本机查询发送到我的数据库。当我这样做时,尽管尝试了很多,但我还没有找到任何方法来做到这一点。

我尝试了许多基于此的语法

String[] values = {"value1", "value2"};
String queryString = "SELECT * FROM instances WHERE values && :values";
Query query = this.getSession().createSQLQuery(queryString).addEntity(Instance.class);
query.setParameterList("values", values);
query.list();

我得到了运算符不存在:文本[] &&字符变化

它应该在jdbc中给出以下语法:['value1','value2'],它似乎给出了'value1'...

我尝试了许多语法

  • 收集
  • 纯数组
  • [ :值 ] 语法 : 我在 “[” 附近出现语法错误

我需要发送本机查询,因为我使用实例化视图来提高性能。

My SQL Query 在 postgresql console 中工作。因此,这是一个休眠的特定问题。


答案 1

我尝试了基于JDBC4引入的数组类型的几个版本:如何将String[]参数设置为本机查询?问题也是休眠(即使在最新版本4.3.1.final中)也无法使用此新功能,并给我以下错误消息

Could not determine a type for class: org.postgresql.jdbc4.Jdbc4Array

因此,我必须创建一个特定的UserType(基于stackoverflow中的几篇文章和其他来源)

我的模特

@Type(type = "fr.mycompany.dao.hibernate.types.ArrayUserType")
private String[] values;

ArrayUserType

public class ArrayUserType implements UserType {

/** Constante contenant le type SQL "Array".
 */
protected static final int[] SQL_TYPES = { Types.ARRAY };

/**
 * Return the SQL type codes for the columns mapped by this type. The
 * codes are defined on <tt>java.sql.Types</tt>.
 * 
 * @return int[] the typecodes
 * @see java.sql.Types
 */
public final int[] sqlTypes() {
    return SQL_TYPES;
}

/**
 * The class returned by <tt>nullSafeGet()</tt>.
 * 
 * @return Class
 */
public final Class returnedClass() {
    return String[].class;
}

/**
 * Retrieve an instance of the mapped class from a JDBC resultset. Implementors
 * should handle possibility of null values.
 * 
 * @param resultSet a JDBC result set.
 * @param names the column names.
 * @param session SQL en cours.
 * @param owner the containing entity 
 * @return Object
 * @throws org.hibernate.HibernateException exception levée par Hibernate
 * lors de la récupération des données.
 * @throws java.sql.SQLException exception SQL 
 * levées lors de la récupération des données.
 */
@Override
public final Object nullSafeGet(
        final ResultSet resultSet, 
        final String[] names, 
        final SessionImplementor session, 
        final Object owner) throws HibernateException, SQLException {
    if (resultSet.wasNull()) {
        return null;
    }

    String[] array = (String[]) resultSet.getArray(names[0]).getArray();
    return array;
}

/**
 * Write an instance of the mapped class to a prepared statement. Implementors
 * should handle possibility of null values. A multi-column type should be written
 * to parameters starting from <tt>index</tt>.
 * 
 * @param statement a JDBC prepared statement.
 * @param value the object to write
 * @param index statement parameter index
 * @param session sql en cours
 * @throws org.hibernate.HibernateException exception levée par Hibernate
 * lors de la récupération des données.
 * @throws java.sql.SQLException exception SQL 
 * levées lors de la récupération des données.
 */
@Override
public final void nullSafeSet(final PreparedStatement statement, final Object value, 
        final int index, final SessionImplementor session) throws HibernateException, SQLException {

    if (value == null) {
        statement.setNull(index, SQL_TYPES[0]);
    } else {
        String[] castObject = (String[]) value;
        Array array = session.connection().createArrayOf("text", castObject);
        statement.setArray(index, array);
    }
}

@Override
public final Object deepCopy(final Object value) throws HibernateException {
    return value;
}

@Override
public final boolean isMutable() {
    return false;
}

@Override
public final Object assemble(final Serializable arg0, final Object arg1)
        throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

@Override
public final Serializable disassemble(final Object arg0) throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

@Override
public final boolean equals(final Object x, final Object y) throws HibernateException {
    if (x == y) {
        return true;
    } else if (x == null || y == null) {
        return false;
    } else {
        return x.equals(y);
    }
}

@Override
public final int hashCode(final Object x) throws HibernateException {
    return x.hashCode();
}

@Override
public final Object replace(
    final Object original,
    final Object target,
    final Object owner) throws HibernateException {
    return original;
}

}

最后一个,但最少的(这是我错过的):当我需要运行SQL本机查询时,我必须使用以下语法强制参数类型

String[] values = ...
Type arrayType = new CustomType(new ArrayUserType());
query.setParameter("value", values, arrayType);

答案 2

与“Damien C”相同的答案,但针对Hibernate v5.4进行了更新(他们的解决方案不再适用于Hibernate v5.4):

import java.io.Serializable;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.CustomType;
import org.hibernate.type.Type;
import org.hibernate.usertype.UserType;

public class ArrayUserType implements UserType {

    protected static final int[] SQL_TYPES = { Types.ARRAY };


    public static Type createCustomType() {
        return new CustomType(new ArrayUserType());
    }

    /**
     * Return the SQL type codes for the columns mapped by this type. The
     * codes are defined on <tt>java.sql.Types</tt>.
     * 
     * @return int[] typecodes
     * @see java.sql.Types
     */
    public final int[] sqlTypes() {
        return SQL_TYPES;
    }

    /**
     * The class returned by <tt>nullSafeGet()</tt>.
     * 
     * @return Class
     */
    public final Class<?> returnedClass() {
        return String[].class;
    }

    /**
     * Retrieve an instance of the mapped class from a JDBC resultset. Implementors
     * should handle possibility of null values.
     * 
     * @param resultSet A JDBC result set
     * @param names Column names
     * @param session  Session in progress
     * @param owner The containing entity 
     * @return Object
     * @throws java.sql.SQLException If the data can't be fetched
     */
    @Override
    public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor session, Object owner)
            throws SQLException {
        if (resultSet.wasNull()) {
            return null;
        }

        return resultSet.getArray(names[0]).getArray();
    }

    /**
     * Write an instance of the mapped class to a prepared statement. Implementors
     * should handle possibility of null values. A multi-column type should be written
     * to parameters starting from <tt>index</tt>.
     * 
     * @param statement A JDBC prepared statement
     * @param value Object to write
     * @param index Statement parameter index
     * @param session Session in progress
     * @throws java.sql.SQLException If the data can't be fetched
     */
    @Override
    public final void nullSafeSet(PreparedStatement statement, Object value, int index, SharedSessionContractImplementor session)
            throws SQLException {

        if (value == null) {
            statement.setNull(index, SQL_TYPES[0]);
        }
        else {
            String[] castObject = (String[]) value;
            Array array = session.connection().createArrayOf("text", castObject);
            statement.setArray(index, array);
        }
    }

    @Override
    public final Object deepCopy(final Object value) {
        return value;
    }

    @Override
    public final boolean isMutable() {
        return false;
    }

    @Override
    public final Object assemble(final Serializable arg0, final Object arg1) {
        return null;
    }

    @Override
    public final Serializable disassemble(final Object arg0) {
        return null;
    }

    @Override
    public final boolean equals(final Object x, final Object y) {
        if (x == y) {
            return true;
        }
        else if (x == null || y == null) {
            return false;
        }
        else {
            return x.equals(y);
        }
    }

    @Override
    public final int hashCode(final Object x) {
        return x.hashCode();
    }

    @Override
    public final Object replace(final Object original, final Object target, final Object owner) {
        return original;
    }
}

并使用它:

String[] values = ...
query.setParameter("myArray", values, ArrayUserType.createCustomType());