How to do multiple column UniqueConstraint in hbm?

前端 未结 3 659
忘掉有多难
忘掉有多难 2020-12-10 01:01

Working on some legacy hibernate code.

How do I do the following with hbm.xml(hibernate mapping file) instead of with annotations?

@Table(name=\"user         


        
相关标签:
3条回答
  • 2020-12-10 01:19

    You can also do this:

      <many-to-one name="client" unique-key="uk1,uk2" .../>
      <property name="username" unique-key="uk1"  .../>
      <property name="email" unique-key="uk2"  .../>
    

    You do not need to use the tag in hbm . If you only want multiple unique constraints.

    0 讨论(0)
  • 2020-12-10 01:23

    Use the 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>
    ...
    

    Documentation extract :

    The <properties> element allows the definition of a named, logical grouping of the properties of a class. The most important use of the construct is that it allows a combination of properties to be the target of a property-ref. It is also a convenient way to define a multi-column unique constraint.

    All available options are described in the Hibernate documentation.

    0 讨论(0)
  • 2020-12-10 01:42

    You can add same unique-key attribute to two different columns. This will create composite unique key.

    <property name="firstName" column="first_name" unique-key="name" />
    <property name="lastName" column="last_name" unique-key="name" />
    

    In the above example the unique key will be created from both first_name and last_name column.

    0 讨论(0)
提交回复
热议问题