在根条件Hibernate 3.6中使用默认表别名

irtuqstp  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(93)

我想将执行的sql的table-alias更改为temp,而不是this。但是,将新别名设置为getSession().createCriteria(Vehicle.class, "temp");不会改变结果。
如前所述,我使用的是Hibernate标准API。
目前我被Hibernate3.6.10.Final卡住了。
我得到是:

/* criteria query */ select this_.vehicle_id as y0_, this_.vin as y1_,this_.initial_registration as y2_ from vehicle this_ where this_.vin=?

我所期待的:

/* criteria query */ select temp.vehicle_id as y0_, temp.vin as y1_,temp.initial_registration as y2_ from vehicle temp where temp.vin=?

简化示例

protected List<T> findByProjectionCriteria() {

    Criteria cr = getSession().createCriteria(Vehicle.class, "temp");
    cr.setResultTransformer(Transformers.aliasToBean(Vehicle.class));

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("vehicleId"), "vehicleId");
    projectionList.add(Projections.property("vin"), "vin");
    projectionList.add(Projections.property("initialRegistration"), "initialRegistration");
    cr.setProjection(projectionList);

    cr.add(Restrictions.eq("vin", "WVW29343249702776"));
            
    begin();
    
    List<T> list = null;
    try {
        list = cr.list();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (list == null)
        list = new ArrayList<T>();

    commit();
    return list;
}

实体

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.*;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@Table(name = "vehicle")
public class Vehicle {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "vehicle_id", unique = true, nullable = false)
    private int vehicleId;
    
    @Column(nullable = false, length = 17)
    private String vin;
    
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "initial_registration")
    private Date initialRegistration;
    
}

我可以做些什么来强制执行所需的行为?

hjzp0vay

hjzp0vay1#

我查看了源代码以及Hibernate是如何处理根别名的。
SessionImpl中的list方法(从我的方法调用)创建了一个新的CriteriaLoader-object,该对象还调用CriteriaQueryTranslator对象的构造函数,其中还设置了默认根别名。
CriteriaQueryTranslator-构造函数中,调用以下方法,该方法负责在查询中设置别名。

private void createCriteriaSQLAliasMap() {
    int i = 0;
    Iterator criteriaIterator = criteriaEntityNames.entrySet().iterator();
    while ( criteriaIterator.hasNext() ) {
        Map.Entry me = ( Map.Entry ) criteriaIterator.next();
        Criteria crit = ( Criteria ) me.getKey();
        String alias = crit.getAlias();
        if ( alias == null ) {
            alias = ( String ) me.getValue(); // the entity name
        }
        criteriaSQLAliasMap.put( crit, StringHelper.generateAlias( alias, i++ ) );
    }
    criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias );
}

在这个方法中,我的别名在while循环中被添加到map中,但后来在map中被替换,因为有相同的键,它是我的实体的类,以标准的形式。

相关问题