如何在hibernate 5中执行like操作

How to perform like operation in hiberante 5

如何在 hibernate 5 中执行以下查询?

select * form product where name like "%s%" or sku like "%s%"

到目前为止,我正在使用以下代码,但它不起作用。

searchText = "%" + searchText + "%";
// Search the text.
try {
    // Get the record with the username.
    SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    CriteriaQuery<ProductsEntity> criteriaQuery = criteriaBuilder.createQuery(ProductsEntity.class);
    Root<ProductsEntity> root = criteriaQuery.from(ProductsEntity.class);

    Predicate[] predicates = new Predicate[2];
    predicates[0] = criteriaBuilder.like(root.get(ProductsEntity_.name), searchText);
    predicates[1] = criteriaBuilder.like(root.get(ProductsEntity_.sku), searchText);
    criteriaQuery.select(root).where(criteriaBuilder.or(predicates));
    Query<ProductsEntity> query = session.createQuery(criteriaQuery);
    List<ProductsEntity> productsEntityList = query.getResultList();

    productsEntityObservableList.setAll(productsEntityList);

    // Set the product table view to the observable list.
    tvProductsList.getItems().clear();
    tvProductsList.getItems().addAll(productsEntityObservableList);
    } catch (HibernateException e ){
                WindowsUtility.displayAlert("Database Error", "Unable to connect to database", Alert.AlertType.ERROR);
                e.printStackTrace();
}

出现以下错误:

Information:java: Errors occurred while compiling module 'RestrauntManagementSystem' Information:javac 1.8.0_201 was used to compile java sources Information:3/14/19 10:51 PM - Compilation completed with 2 errors and 4 warnings in 2 s 254 ms Warning:java: source value 1.5 is obsolete and will be removed in a future release Warning:java: target value 1.5 is obsolete and will be removed in a future release Warning:java: To suppress warnings about obsolete options, use -Xlint:-options. /home/kazekage/IdeaProjects/RestrauntManagementSystem/src/main/java/admin/ProductsController.java Warning:(258, 27) java: isNumber(java.lang.String) in org.apache.commons.lang3.math.NumberUtils has been deprecated Error:(288, 63) java: cannot find symbol symbol: variable ProductsEntity_ location: class admin.ProductsController Error:(289, 63) java: cannot find symbol symbol: variable ProductsEntity_
location: class admin.ProductsController

like 是 jpql 和 hql 中的有效关键字,因此您可以轻松地在 @Query 或任何其他方式中使用它。示例:

@Query("select e from Entity e where e.someField like :param")
public Entity getEntityBySomeField(@Param("param") String param);