首页 文章

Hibernate按分离表中的列顺序排序

提问于
浏览
0

我有4张 table . 对于这个问题,我将它们命名为tableA,tableB,tableC,tableD .

tableB看起来像这样:id,name,label,some_other_parameters

tableC看起来像这样:id,code,some_other_parameters

tableD列:id,tableA_id,tableB_id,tableC_id,entityVersion

tableD中的列没有在实体中定义一对多,多对一关联 . 它无法改变 . 无所谓,但无法改变 . 列的定义如下所示:@Column(name - “T_tableA_ID”)private Long tableAId;

对于tableB和tableC,列定义看起来相同 .

插入时,tableD中的行如下所示:

tableA不为null,tableB不为null,tableC为null

要么:

tableA不为null,tableB为null,tableC不为null

我想按顺序从tableD获取列表:tableB行按标签排序|| ''|| name asc - (标签对于不同的行可以是相同的,名称是唯一的)然后tableC行按代码asc排序

甚至可能在标准中这样做吗?

现在我创建了tableD的视图和视图列表 . 当我在tableD中更新或插入行时,我使用table的实体 . 所以我有两个实体:view(有列display_name,我按此列命令)和table(用于插入和更新) . 但这个解决方案对我来说并不完美 . 我更喜欢使用标准 .

我在标准中需要这样的东西:

select * from 
TABLE_D tab_d
where TABLE_A_ID = 1 --example id
order by TABLE_B_ID,
case when TABLE_B_ID is not null then
(select code from TABLE_B where id = tab_d.TABLE_B_ID) 
else
(select label || ' ' || name from TABLE_C where id = tab_d.TABLE_C_ID)
end

另一个以我需要的方式返回排序数据的sql:

select tab_d.* from
table_d tab_d
left join table_b tab_b on tab_b.id = tab_d.t_groups_id
left join table_c tab_c on tab_c.id = tab_d.t_users_id
where table_a_id = 10485
order by tab_d.t_groups_id, tab_b.code, tab_c.name || ' ' || tab_c.surname

可以为第一个或第二个sql语句创建条件吗?

1 回答

  • 0

    您可以扩展org.hibernate.criterion.Order并提供自己的实现,为Order生成SQL . 见the code example

    public class OrderBySqlFormula extends Order {
        private String sqlFormula;
    
        /**
         * Constructor for Order.
         * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
         */
        protected OrderBySqlFormula(String sqlFormula) {
            super(sqlFormula, true);
            this.sqlFormula = sqlFormula;
        }
    
        public String toString() {
            return sqlFormula;
        }
    
        public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
            return sqlFormula;
        }
    
        /**
         * Custom order
         *
         * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
         * @return Order
         */
        public static Order sqlFormula(String sqlFormula) {
            return new OrderBySqlFormula(sqlFormula);
        }
    }
    

    然后只需使用您的订单

    criteria.addOrder(OrderBySqlFormula.sqlFormula("(a + b) desc"));
    

相关问题