一尘不染

没有基础表的休眠实体

hibernate

我有一个非常丑陋的旧数据库系统,需要与之集成。本质上,我在系统上做一些只读报告,并且我不想建立代表我正在处理的每个表的上千个实体。相反,我只想为我生成的每种报告类型定义一个实体(本质上是来自不同表的一堆列的并集),然后让讨厌的hibernate映射(许多已加入,很多已合并)
sql查询到此类实体的列表。

问题是:我可以创建一个没有基础表的实体,并使用sql语句填充所述实体的列表吗?

谢谢!


阅读 198

收藏
2020-06-20

共1个答案

一尘不染

我们一直在做这种事情-这是我们的做事方式:

  1. 定义一个简单的类似于bean的对象来表示报告中的每一行输出:

    public class CityStateRevenueReport {
    
    private String mId;
    private String mState;
    private String mCity;
    private Double mRevenue;
    
    public String getId() { return mId; }
    public void setId(String i) { mId = i; }
    public String getState() { return mState; }
    public void setState(String s) { mState = s; }
    public String getCity() { return mCity; }
    public void setCity(String c) { mCity = c; }
    public Double getReveneue() { return mRevenue; }
    public void setRevneue(Double d) { mRevenue = d; }
    

    }

  2. 定义一个hibernate映射文件CityStateRevneueReport.hbm.xml:

       <?xml version="1.0" ?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;>
    <hibernate-mapping>
        <class entity-name="CityStateRevenueReport">
            <id name="Id" type="java.lang.String" column="report_id">
                <generator class="sequence" />
            </id>
            <property name="city" type="string" column="city" />
            <property name="state" type="string" column="state" />
            <property name="revenue" type="double" column="revenue" />
        </class>
        <sql-query name="runReport">
            <![CDATA[ 
            SELECT {r.*} FROM 
                (select some_id_value as report_id, 
                        state_abbreviation as state, 
                        city_name as city, 
                        dollar_amount as revenue 
                   from -- tables, joins, other SQL insanity 
                 ) r
            ]]>
            <return alias="r" class="CityStateRevenueReport" />
        </sql-query>
    </hibernate-mapping>
  1. 然后运行查询并填充实例:
    public List<CityStateRevenueReport> runReport() {
    
    List<CityStateRevenueReport> reports = 
                             new ArrayList<CityStateRevenueReport>();
    List<HashMap> maps = session.getNamedQuery("runReport").list()
    for ( HashMap map : results ) {
        CityStateRevenueReport report = new CityStateRevenueReport();
        report.setState(map.get("state"));
        report.setCity(map.get("city"));
        report.setRevenue(Double.parseDouble(map.get("revenue"));
        reports.add(report);
    }
    return reports;
    

    }

2020-06-20