[英]JPA - How to query with a LIKE operator in combination with an AttributeConverter
For example Customer
has a field of type PhoneNumber
(value object). 例如,
Customer
有一个PhoneNumber
类型的字段(值对象)。 In the persistence.xml
a PhoneNumberConverter
is registered which implements javax.persistence.AttributeConverter
. 在
persistence.xml
中,注册了一个实现javax.persistence.AttributeConverter
的PhoneNumberConverter
。 This converter converts a PhoneNumber
to string and visa versa, so the JPA provider is able to store PhoneNumbers
into the database. 此转换器将
PhoneNumber
转换为字符串,反之亦然,因此JPA提供程序能够将PhoneNumbers
存储到数据库中。
How to query a Customer
with a LIKE
operator on PhoneNumber
with the Criteria API? 如何使用Criteria API在
PhoneNumber
使用LIKE
运算符查询Customer
? PhoneNumber
can only be a valid phone number. PhoneNumber
只能是有效的电话号码。 A PhoneNumber
with a value like '+31%'
is not possible. 无法使用值为
'+31%'
PhoneNumber
。
The simple answer is to use a NamedQuery
, but you could also use a CriteriaBuilder
. 简单的答案是使用
NamedQuery
,但您也可以使用CriteriaBuilder
。 Note that you will have to provide the correct types and search terms. 请注意,您必须提供正确的类型和搜索字词。
Something like this: 像这样的东西:
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();
public List<Customer> findCustomerByPhoneNumber(String phoneNumber) {
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> cq = criteriaBuilder.createQuery();
Root<Customer> customer = criteriaQuery.from(Customer.class);
Predicate predicate = cb.like(customer.get(Customer_.phoneNumber).as(String.class), phoneNumber);
cq.where(predicate);
TypedQuery<Customer> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
Where phoneNumber
may include the character %
. 其中
phoneNumber
可能包含字符%
。
The solution of the problem is in the casting to String
of PhoneNumber
: .as(String.class)
. 该问题的解决方案是转换为
PhoneNumber
String
: .as(String.class)
。 PhoneNumber
has to override the methode toString ()
and return the phone number. PhoneNumber
必须覆盖方法toString ()
并返回电话号码。
( Customer_
provides the meta model of Customer
and may be generated by a metamodel generator .) (
Customer_
提供的元模型Customer
并且可以由生成元模型发生器 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.