简体   繁体   English

该查询的休眠等效项是什么(添加两列)

[英]What is the Hibernate Equivalent of this query?(Adding Two Columns)

This is the query 这是查询

SELECT id, name, sub1, sub2, sub1 + sub2 AS total 
FROM mytable 
ORDER BY sub1 + sub2 ASC

What I am trying to do here is that I will add sub1 and sub2 and the result would be named TOTAL, and I will use TOTAL for Order By. 我在这里尝试做的是添加sub1和sub2,结果将被命名为TOTAL,并且我将TOTAL用于Order By。 so far this is how I've come up with but it is not rendering proper reults 到目前为止,这是我想出的方法,但是没有给出正确的结果

sess().createSQLQuery("SELECT *, SUB1+ SUB2 AS TOTAL FROM TRACKS order by TOTAL ").addEntity(Student.class).list();

What is the hibernate or Query Criteria equivalent of what I am trying to do? 我试图做的休眠或查询条件等效项是什么?

there is no such operation in JPQL, But what you could do is do a native query as follows: JPQL中没有这样的操作,但是您可以做的是执行本地查询,如下所示:

"SELECT * FROM TRACKS order by SUB1+ SUB2"

And make a getter like: 然后做一个吸气剂:

public Double getTotal(){ //Replace Double for the data type you use
    return sub1 + sub2;
}

That way you could order the query as you want. 这样,您可以根据需要订购查询。

Is this what you're trying to do? 这是您要做什么? I'm not sure if I understood quite well your question 我不确定我是否很好理解你的问题

I would say, that you have two options: Mapping or custom OrderBy object. 我要说的是,您有两个选择:映射或自定义OrderBy对象。

1) Mapping: If the Total would be used often, you can extend your entity mapping and create calculated/readonly property (seee 5.1.11. Property ): 1)映射:如果Total将被经常使用,可以延长你的实体映射和创建计算/只读属性(SEEE 5.1.11属性。 ):

<property name="total" formula="(sub1 + sub2)" insert="false" udpate="false" />

Now, we can use this value for Order by easily (and anywhere): 现在,我们可以轻松地(在任何地方)将此值用于Order:

Criteria criteria = session.createCriteria(MyClass.class);
...
criteria.addOrder(Order.asc("total"));

2) We are still in the OOP world. 2)我们仍然在OOP世界中。 The criteria.addOrder() operation, expects the Order object instance. criteria.addOrder()操作需要Order对象实例。 So we can pass the Custom one: 'MyOrder'. 因此,我们可以传递自定义变量:“ MyOrder”。 In our case, it could be object accepting any valid SQL statement and directly inject that into ORDER BY: 在我们的例子中,它可能是对象接受任何有效的 SQL语句,然后将其直接注入ORDER BY:

public class MyOrder extends Order {
    public MyOrder(String propertyName, boolean ascending) {
        super(propertyName, ascending);
    }

    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) {
        StringBuilder fragment = new StringBuilder();
        fragment.append(propertyName );
        fragment.append( ascending ? " asc" : " desc" );
        return fragment.toString();
    }
}

Now, we can inject any (valid) SQL Script into ORDER BY this way: 现在,我们可以通过这种方式将任何(有效)SQL脚本注入到ORDER中:

Criteria criteria = session.createCriteria(MyClass.class);
...
criteria.addOrder(new MyOrder("(sub1 + sub2)", true));

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

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