【问题标题】:Convert query to hibernate criteria query将查询转换为休眠条件查询
【发布时间】:2012-10-18 20:04:43
【问题描述】:

我有以下 Sybase 查询,

select *
  from dbo.translation_style_sheet t1
 where t1.create_date = (select max(t2.create_date) 
                           from dbo.translation_style_sheet t2
                          where t1.file_name = t2.file_name);

我正在尝试将其转换为休眠条件查询,但无法弄清楚。我假设我需要使用 DetachedCriteria 来处理这个问题,但不确定如何使用它。

这是我迄今为止所拥有的。

DetachedCriteria maxCreateDate = DetachedCriteria.forClass(TranslationStyleSheet.class, "translationStyleSheet2")
    .setProjection( Property.forName("createDate").max() )
    .add( Property.forName("translationStyleSheet2.fileName").eqProperty("translationStyleSheet.fileName") );

List<TranslationStyleSheet> translationStyleSheets = this.session.createCriteria(TranslationStyleSheet.class, "translationStyleSheet")
            .add( Property.forName("createDate").eq(maxCreateDate))
            .list();

我收到以下异常。

org.hibernate.exception.GenericJDBCException
could not execute query

SQL
    select this_.translation_style_sheet_id as translat1_20_0_, this_.create_date as create2_20_0_, this_.description as descript3_20_0_, this_.file_content as file4_20_0_, this_.file_extension as file5_20_0_, this_.file_name as file6_20_0_, this_.file_size as file7_20_0_, this_.style_sheet_content as style8_20_0_, this_.style_sheet_type as style9_20_0_ from translation_style_sheet this_ where this_.create_date = (select max(translationStyleSheet2_.create_date) as y0_ from translation_style_sheet translationStyleSheet2_ where translationStyleSheet2_.file_name=this_.file_name)
SQLState
    ZZZZZ

有人知道我做错了什么吗?

更新

错误似乎发生在 max(translationStyleSheet2_.create_date) as y0_ 作为。当我在 sql 语句中删除 as y0_ 时,我可以运行查询查询,但是我不确定如何在休眠条件中修复它。

【问题讨论】:

  • 为什么要使用 PostgreSQL 和 MySQL 标签?
  • @Craig Ringer,我不认为这个问题与数据库的类型直接相关,而是与休眠有关。我的假设是任何使用这些数据库的任何人都可以帮助我解决我的问题。

标签: mysql hibernate postgresql sybase hibernate-criteria


【解决方案1】:

因此,我没有成功将其用作条件查询,但我确实成功地将其用作 HQL 查询。

HQL 解决方案

this.session.createQuery("from TranslationStyleSheet this "
                + "where this.createDate = (select max(translationStyleSheet2.createDate) "
                + "from TranslationStyleSheet translationStyleSheet2 "
                + "where translationStyleSheet2.fileName=this.fileName)")
                .list();

不过,我仍然有兴趣让查询作为条件查询工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2018-12-19
    • 2016-01-03
    • 2023-04-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多