Параметр 0 функции «array_position()» требует типа массива, но аргумент имеет тип «java.util.List».JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Параметр 0 функции «array_position()» требует типа массива, но аргумент имеет тип «java.util.List».

Сообщение Anonymous »

В настоящее время я работаю над проектом Quarkus, который использует Hibernate и построитель критериев для доступа к данным в базах данных postrgresql.
Недавно мы обновили спецификацию Quarkus, которая включала обновление Hibernate (ядро) с версии с 6.2 по 6.6. После обновления мы теперь получаем сообщение об ошибке при построении команды postgresql с использованием jakarta.persistence.criteria.CriteriaBuilder:

Код: Выделить всё

Parameter 0 of function 'array_position()' requires an array type, but argument is of type 'java.util.List'
Эта конкретная ошибка выдается в этой подфункции в последней строке:

Код: Выделить всё

    /**
* Creates an expression that can be used to determine if the array at the given path contains the given element.
*
* @param criteriaBuilder The criteria builder.
* @param arrayPath       The path to the array.
* @param element         The element to look for.
* @param              The type of the elements in the array. The element must have the same type.
* @return The expression to check an array for the given element.
*/
public  Predicate createArrayContainsExpression(final CriteriaBuilder criteriaBuilder,
final Path arrayPath,
final Expression element) {
// array_position($array, $element) returns the index of $element in $array or NULL, if it is not contained.
// If looking for null, we pass null for $element, the result will be non-null (an integer),
// if the array contains null or null if the array does not contain null. That's why we check the result with
// IS NOT NULL. This is more intuitive for non-null values of element.
// The following code translates to the SQL:
// array_position(array, $element) IS NOT NULL
return criteriaBuilder.isNotNull(criteriaBuilder.function(
"array_position",
Boolean.class,
arrayPath,
element
));
}
Входной путь массива createArrayContainsExpression указывает на поле класса сущности, что, по-видимому, и является проблемой. Вот минимальный пример:

Код: Выделить всё

    @Column(name = "demand_types")
@JdbcTypeCode(Types.ARRAY)
@Convert(converter = DemandType.DemandTypeListConverter.class)
private List demandTypes;
DemandTypeListConverter реализует AttributeConverter (см. ниже) и отвечает за преобразование между коротким значением в базе данных и перечислениями в Java (

Код: Выделить всё

DemandType
— это перечисление).

Код: Выделить всё

public interface DbEnum {
Short getDbValue();

static  T convert(Class enumClass, Short value) {
Short nonNullValue = value == null ? -1 : value;

return Stream.of(enumClass.getEnumConstants())
.filter(c -> c.getDbValue().equals(nonNullValue))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}

abstract class EnumConverter implements AttributeConverter {

/**
* Maps enum values to database values of type short/smallint
*
* @param dbEnum the enum value that should be mapped to a database entry
* @return the integer value corresponding to the enum value.
*/
@Override
public Short convertToDatabaseColumn(T dbEnum) {
if (dbEnum == null) {
return null;
}
return dbEnum.getDbValue();
}
}

/**
* Base class for converters between list typed {@link DbEnum} entity attributes and smallint / short typed database
* array attributes.
*
* @param  The concrete type of {@link DbEnum}.
*/
abstract class EnumListConverter implements AttributeConverter[*], Short[]> {
@Override
public final Short[] convertToDatabaseColumn(final List attribute) {
if (attribute == null) {
return null;
}

Short[] dbValues = new Short[attribute.size()];
for (int i = 0; i < attribute.size(); i++) {
dbValues[i] = attribute.get(i).getDbValue();
}
return dbValues;
}

@Override
public final List convertToEntityAttribute(final Short[] dbData) {
if (dbData == null) {
return null;
}

List dbEnumList = new ArrayList();
for (Short dbValue : dbData) {
final T converted = convert(dbValue);
dbEnumList.add(converted);
}
return dbEnumList;
}

public abstract T convert(final Short dbValue);
}
}
Что я уже пробовал?
  • Используя более старую версию Quarkus-Bom, которая включает более старые версии спящего режима. Не сработало, так как старые версии Quarkus-Bom приводили к той же проблеме. Кроме того, более старые версии Quarkus-Bom включают CVE, который я пытался удалить в первую очередь.
  • Используйте массивы Java вместо списков в моем классе сущностей. Это решило аналогичную проблему:

    Код: Выделить всё

    Parameter 0 of function 'array_position()' requires an array type, but argument is of type 'com.bmw.ispi.leads.cockpit.lead.handling.entity.enums.NotificationStatus[]'
  • Пытался использовать проблему GitHub https://github.com/vladmihalcea/hypersi ... issues/708, которая, похоже, имела похожую тему. Однако я не полностью соответствовал своей проблеме, как я узнал после дальнейшего расследования.
Есть ли у кого-нибудь дополнительные идеи, в чем может быть проблема и как мне может решить эту проблему?

Подробнее здесь: https://stackoverflow.com/questions/793 ... t-argument
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»