mysql - 将查询转换为 hibernate 条件查询

标签 mysql hibernate postgresql sybase hibernate-criteria

我有以下 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);

我正在尝试将其转换为 hibernate 条件查询,但无法弄清楚。我假设我需要使用 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

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

更新

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

最佳答案

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

HQL解决方案

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

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

关于mysql - 将查询转换为 hibernate 条件查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13122799/

相关文章:

java - 错误 : java. lang.ClassCastException

mysql - 使用带注释的 OneToMany 单向映射时,为什么 POJO 属性位置在数据库 MySql 中发生变化?

sql - 如何在 Postgres 中使用 upsert

MySQL删除子查询中的重复子句

java - jdbc连接mysql时访问被拒绝

mysql - Docker OpenProject 数据库到 MySQL

mysql - 在 SQL 中创建排名系统,变量问题

java - Hibernate - 有没有办法将 2 列与 1 列连接起来?

sql - Postgres 9.0 慢查询

java - maven 启动 postgres 服务器