Java hbm.xml 一列的多个索引

Java hbm.xml multiple index of one column

例如,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.sql.index">
    <class name="User">
        <id name="id" type="long">
            <generator class="native" />
        </id>
        <property name="firstName" type="string" index="IDX_FIRST_NAME" />
        <property name="lastName" type="string" />
        <property name="address" type="string" />
        <property name="field_1" type="long" />
        <property name="field_2" type="long" />
    </class>
</hibernate-mapping>

如果我想要 field_1field_2 有 2 个索引描述。我可以做以下事情吗?或者如何实现?

        <property name="field_1" type="long" index="idx_1,idx_2"/>
        <property name="field_2" type="long" index="idx_1,idx_3"/>

field_1field_2 将有 2 个索引。


我参考了hibernate 3.6, 5.1.4.2 Property mapping with hbm.xml,好像index字段可以被only one column赋值。


PS,

项目比较老,维护的人很多,所以不能用注解语法添加index

我找到了 post 并试一试。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.sql.index">
    <class name="User">
        <id name="id" type="long">
            <generator class="native" />
        </id>
        <property name="firstName" type="string" index="IDX_FIRST_NAME" />
        <property name="lastName" type="string" />
        <property name="address" type="string" />
        <property name="field_1" type="long" index="idx_2"/>
        <property name="field_2" type="long" index="idx_3"/>
    </class>
    <database-object>
        <create>
            CREATE INDEX idx_1 ON User (field_1, field_2)
        </create>
        <drop></drop>
    </database-object>
</hibernate-mapping>

此问题可以通过 <database-object> 解决,方法是编写本机 sql 语法来创建索引。


更新,2018/11

对于具有多个属性的唯一约束,someone has answered it

Use properties tag

<properties name="uk1" unique="true">
        <property name="username" .../>
        <many-to-one name="client" .../>
</properties>

<properties name="uk2" unique="true">
        <property name="email" .../>
        <many-to-one name="client" update="false" insert="false" .../>
</properties>