JPA-如何与LIKE运算符结合AttributeConverter进行查询 [英] JPA - How to query with a LIKE operator in combination with an AttributeConverter

查看:183
本文介绍了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();

这篇关于JPA-如何与LIKE运算符结合AttributeConverter进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆