java – jpa AttributeConverter是否适用于查询子句?
作者:互联网
我有一个像这样的jpa实体:
@Entity
public class RectangleEntity
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private Integer x;
@Column
private Integer y;
@Column
@Convert(converter = ColorConverter.class)
private Color color;
}
我的ColorConverter是这样的:
@Converter
public class ColorConverter implements AttributeConverter<Color, String[]> {
@Override
public String[] convertToDatabaseColumn(Color color) {
switch(color) {
case REDISH : return {"red","pink"};
case GREENISH: return {"green","cyan"};
}
return sb.toString();
}
@Override
public Color convertToEntityAttribute(String... colorStrings) {
if(colorStrings == null || colorStrings.length != 1) {
return null;
}
if(colorStrings[0].equals("red") || colorStrings[0].equals("pink")) {
return REDISH;
} else if(colorStrings[0].equals("green") || colorStrings[0].equals("cyan")) {
return GREENISH;
}
}
}
问题是我想在这样的查询中使用我的列值:
Expression<String> colorPath = root.get("color");
Predicate predicate = requestStatePath.in(Color.REDISH);
Predicate[] predicatesArr = predicates.toArray(new Predicate[predicates.size()]);
criteriaQuery.where(predicatesArr);
CriteriaQuery<RectangleEntity> criteriaQuery = criteriaBuilder.createQuery(RectangleEntity.class);
TypedQuery<RectangleEntity> query = this.em.createQuery(criteriaQuery);
query.getResultList();
我想要这个查询选择我的所有记录,他们的颜色字段是粉红色或红色,因为它们是REDISH.
可能吗?
解决方法:
我不认为你的转换器正在做你想做的事情.首先,根据JPA,实现甚至不是有效的AttributeConverter. JPA仅定义对基本类型的AttributeConverters的支持,并不认为String []是基本类型.虽然Hibernate允许String [],但它只会将其视为Serializable.
你期望存储这些String []到DB ARRAY吗?如果是这样,Hibernate不支持DB ARRAY类型(但是,我们一直在谈论在6.0中添加对它们的支持).
但要回答你的确切问题……是的,JPA表示AttributeConverter应该在3.8节中概述的某些指导原则中自动应用于查询中:
… The persistence provider must apply any conversion methods to
instances of attribute values in path expressions used within Java Persistence query language queries or
criteria queries (such as in comparisons, bulk updates, etc.) before sending them to the database for the
query execution. When such converted attributes are used in comparison operations with literals or
parameters, the value of the literal or parameter to which they are compared must also be converted. …
但是你最终会得到一个类似< BINARY>的谓词.在< BINARY>中
标签:java,jpa,hibernate,jpa-2-1 来源: https://codeday.me/bug/20190706/1394119.html