JPA-如何与LIKE运算符结合AttributeConverter进行查询

问题描述:

例如 Customer 的字段类型为 PhoneNumber (值对象)。
persistence.xml 中注册了一个 PhoneNumberConverter ,它实现了 javax.persistence。 .AttributeConverter 。该转换器将 PhoneNumber 转换为字符串,反之亦然,因此JPA提供程序能够将 PhoneNumbers 存储到数据库中。

For example Customer has a field of type PhoneNumber (value object). In the persistence.xml a PhoneNumberConverter is registered which implements javax.persistence.AttributeConverter. This converter converts a PhoneNumber to string and visa versa, so the JPA provider is able to store PhoneNumbers into the database.

如何使用 Like 运算符查询客户在带有Criteria API的 PhoneNumber 上? 电话号码只能是有效的电话号码。 PhoneNumber 的值不能为'+ 31%'

How to query a Customer with a LIKE operator on PhoneNumber with the Criteria API? PhoneNumber can only be a valid phone number. A PhoneNumber with a value like '+31%' is not possible.

简单的答案是使用 NamedQuery ,但是您也可以使用 CriteriaBuilder 。请注意,您必须提供正确的类型和搜索词。

The simple answer is to use a NamedQuery, but you could also use a CriteriaBuilder. Note that you will have to provide the correct types and search terms.

类似这样的东西:

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery();
Root root = criteriaQuery.from(/*The class youre searching*/);
Predicate predicate = criteriaBuilder.like(root.<String>get(/*field name*/), /*search values*/);
criteriaQuery.where(predicate);
criteriaQuery.select(root);
TypedQuery query = entityManager.createQuery(criteriaQuery);
List<T> result = query.getResultList();