如何为这种情况创建hibernate映射?

时间:2014-09-26 14:36:32

标签: java mysql sql xml hibernate

我有以下SQL查询:

    SELECT CONNECTIONDATE AS UNLOAD, 
    SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2)) AS ROUTE, 
    COUNT(SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2))) AS FREQUENCY 
    FROM RouteTableSynonym RC1 
    WHERE RC1.ROUTECONNECTIONTYPE = 'INBOUND' 
    and RC1.CONNECTIONTIME >= TO_TIMESTAMP('<sdate>', 'DD-MM-YYYY HH24:MI:SS') 
    and RC1.CONNECTIONTIME <= TO_TIMESTAMP('<edate>', 'DD-MM-YYYY HH24:MI:SS') 
    and RC1.LOGISTICSPOINTID in (SELECT DISTINCT RCO1.LOGISTICSPOINTID  
    FROM RouteOrderTableSynonym RCO1 
    WHERE RCO1.NAMC = '<namc>') 
    GROUP BY CONNECTIONDATE, SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2)) 
    ORDER BY CONNECTIONDATE, ROUTE;

由&#39;&lt; var_name &gt;&#39;指定的所有值被替换为被查询的值。我也有这个实体类来存储这个查询的结果:

   import java.util.Date;

   public class DD_BlackoutRouteFrequencies {

        private Date rte_day;
        private String route;
        private int freq;
        private int delayedFreq;

        public Date getRte_day() {
            return rte_day;
        }
        public void setRte_day(Date rte_day) {
            this.rte_day = rte_day;
        }
        public String getRoute() {
            return route;
        }
        public void setRoute(String route) {
            this.route = route;
        }
        public int getFreq() {
            return freq;
        }
        public void setFreq(int freq) {
            this.freq = freq;
        }
        public int getDelayedFreq() {
            return delayedFreq;
        }
        public void setDelayedFreq(int delayedFreq) {
            this.delayedFreq = delayedFreq;
        }   
    }

我执行这样的查询:

    try{
        SQLQuery sqlquery = session.createSQLQuery(query);
        sqlquery.addEntity(DD_BlackoutRouteFrequencies.class);
        results = sqlquery.list();
        logger.debug(results.size());
        System.out.println("Frequnecy Results size: "+results.size());
    }catch(Exception e){
        logger.error("Exception ", e);
        throw new RuntimeException("SQL Exception getting Blackout Route Frequencies: "+ e.getMessage());
    }

我遇到的问题是我无法弄清楚如何为此实体执行hibernate映射以接收此查询的结果,该查询从两个不同的表中获取结果。

我是否必须为查询中使用的两个表执行hibernate映射,然后映射实体?

1 个答案:

答案 0 :(得分:0)

您还可以获取地图的实例。 e.g:

SQLQuery sqlQuery = session.createSQLQuery(sql);

// positional parameters (using ?)
sqlQuery.setString(0, sdate);
sqlQuery.setString(1, edate);
sqlQuery.setString(2, namc);

// scalar values for each column
sqlQuery.addScalar("UNLOAD", Hibernate.STRING);
sqlQuery.addScalar("ROUTE", Hibernate.STRING);
sqlQuery.addScalar("FREQUENCY ", Hibernate.INTEGER);

sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
List<Map<String, Object>> list = sqlQuery.list();

for (Map<String, Object> map : list) {
    System.out.println(map.get("UNLOAD"));
    System.out.println(map.get("ROUTE"));
    System.out.println(map.get("FREQUENCY"));
}