如何在hiberante 5中执行类似的操作

时间:2019-03-14 17:09:16

标签: java hibernate jpa

如何在休眠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();
}

发生以下错误:

  

信息:java:编译模块时发生错误   “ RestrauntManagementSystem”信息:javac 1.8.0_201用于   编译Java源信息:19/3/14 10:51 PM-编译   在2 s 254毫秒内完成了2个错误和4个警告,警告:java:   源值1.5已过时,将在以后的版本中删除   警告:java:目标值1.5已过时,将在   将来的版本警告:java:抑制有关过时的警告   选项,请使用-Xlint:-options。   /home/kazekage/IdeaProjects/RestrauntManagementSystem/src/main/java/admin/ProductsController.java   警告:(258,27)java:isNumber(java.lang.String)在   org.apache.commons.lang3.math.NumberUtils已弃用   错误:(288,63)Java:找不到符号符号:变量   ProductsEntity_位置:类admin。ProductsController错误:(289,   63)Java:找不到符号符号:变量ProductsEntity_
  位置:类admin.ProductsController

1 个答案:

答案 0 :(得分:1)

select * from test where date > '%0:01%' 在jpql和hql中都是有效的关键字,因此您可以轻松地在like中或以任何其他方式使用它。示例:

@Query