我的Hibernate hbm文件与mysql DB看起来像这样:
<hibernate-mapping>
<class name="com.company.common.bo.position.Parent" table="Parents"
abstract="true">
<id name="id">
<generator class="increment" />
</id>
<property name="date" not-null="true" />
<property name="milliseconds" not-null="true" />
<property name="shares">
<column name="shares" precision="19" scale="6" not-null="true" />
</property>
<many-to-one name="ticker" column="tickerID" not-null="true" index="_tickerID_date_milliseconds_idx" />
<many-to-one name="auditTrail" column="auditTrailID"
not-null="false" cascade="save-update" lazy="false" fetch="select" />
<union-subclass name="com.company.common.bo.position.SubclassA"
table="SubclassAs">
<many-to-one name="account" column="accountID" not-null="true" foreign-key="SubclassA_accountID_fk" />
<many-to-one name="portfolio">
<column name="portfolioID" not-null="true"/>
</many-to-one>
<many-to-one name="individualTrade">
<column name="individualTradeID" not-null="false"/>
</many-to-one>
<many-to-one name="positionTransfer" column="positionTransferID"
cascade="save-update" not-null="false"/>
</union-subclass>
<union-subclass
name="com.company.common.bo.position.SubclassB" table="SubclassBs">
<many-to-one name="individualTrade">
<column name="individualTradeID" not-null="false" />
</many-to-one>
<many-to-one name="account" column="accountID" not-null="true" foreign-key="SubclassBs_accountID_fk"/>
<many-to-one name="internalExecution" column="executionID"
cascade="save-update" not-null="false" />
</union-subclass>
<union-subclass name="com.company.common.bo.position.SubclassC"
table="SubclassCs">
</union-subclass>
</class>
所以基本上我有一个抽象类Parent和3个子类(SubclassA,B,C)来扩展它。在数据库中有3个表(对于3个子类)。 id生成器是“increment”,因为union子类映射不允许我使用native。因此看起来像增量,ID在3个表中是唯一的。当我查看hibernate sql时,它基本上从所有3个表中找到最大ID,并将其用作下一个ID。但它使用的查询似乎非常低效。这就是我所看到的:
select max(ids_.id) from ( select id from SubclassAs union select id from SubclassBs union select id from SubclassCs ) ids_
运行需要12秒。每个表中的每一个都有超过一百万条记录。它将每个ID组合在一起,然后选择最大值。
如果我做这样的事情:
select max(ids_.id) from ( select max(id) as id from SubclassAs union select max(id) as id from SubclassBs union select max(id) as id from SubclassCs ) ids_
速度快得多,小于1毫秒,因为内部联合只从每个表中获取最大值,然后我只选择这3条记录中的最大值。
有没有办法告诉hibernate这样做,或者是否有更好的方法在这3个表中使用生成器作为ID?
由于