简体   繁体   English

如何使用JPA查询生成器在SQL中使用日期函数

[英]how to use date function in sql using jpa query builder

I am using following code to search table records based on the date but I am getting error while using the date function to_char 我正在使用以下代码根据日期搜索表记录,但是在使用日期函数to_char时出现错误

public List<TeacherTaskAllocation> searchTasks(String TeacherName, Date OnDate){
    EntityManager em=getEntityManager();
    try{
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery cq   = cb.createQuery(TeacherTaskAllocation.class);
        Root<TeacherTaskAllocation> rt = cq.from(TeacherTaskAllocation.class);
         cq.select(rt);
         List<Predicate> conditionList =new ArrayList<Predicate>();
         Predicate condition1,condition2;

         if((TeacherName!=null)&&(!(TeacherName.isEmpty()))){

             condition1=cb.like(cb.upper(rt.<String>get("teacherName")),"%"+TeacherName.toUpperCase()+"%" );

             conditionList.add(condition1);
         }

          if((OnDate!=null)&&(!(TeacherName.isEmpty()))){

          condition2=cb.equal((cb.function("TO_CHAR", "onDate", "dd/Mm/yy")), "%"+OnDate+"%");



             conditionList.add(condition2);
         }
          Predicate[] conditions = new Predicate[conditionList.size()];
          conditionList.toArray(conditions);
          cq.where(conditions); 
          TypedQuery<TeacherTaskAllocation> q = em.createQuery(cq);
          List<TeacherTaskAllocation> list=q.getResultList();
           return list;

    }finally{
        em.close();
    }`

Please can any one suggest me how I can achieve this task, how to use cb.function() in the jpa query builder 请问有人可以建议我如何实现此任务,如何在jpa查询生成器中使用cb.function()

You should compare your param as a date with the date in database, not your param as a string compared to the database date as a string. 您应该将参数作为日期与数据库中的日期进行比较,而不是将参数作为字符串与数据库日期作为字符串进行比较。

Use TO_DATE( string1, [ format_mask ], [ nls_language ] ) 使用TO_DATE( string1, [ format_mask ], [ nls_language ] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM