javahibernatehbmxml

Java hbm.xml multiple index of one column


For example,

<?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>

If I want the field_1 and field_2 has 2 indexes description. Can I do the following thing? Or How to achieve it ?

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

The field_1 and field_2 will has 2 index for their self.


I refer the hibernate 3.6, 5.1.4.2 Property mapping with hbm.xml, it seems like the index field can be assigned by only one column.


PS,

The project is some kind old, and is maintained by many people, so I cannot use annotation syntax to add index.


Solution

  • I found the post and give it a try.

    <?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>
    

    This problem can be solved by <database-object>, by writing native sql syntax to create index.


    UPDATE, 2018/11

    For unique constraint with multiple properties, 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>