Hibernate - automatic and generic way to check if a defined unique key constraint exists?

StackOverflow https://stackoverflow.com/questions/11217746

  •  17-06-2021
  •  | 
  •  

Question

Imagine a City to Postalcode relation mapping. (For simplicity using no foreign-keys)

<class name="CityToPostalcode" table="city_to_postalcode" catalog="database">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <property name="city" type="String">
        <column name="city" not-null="true"/>
    </property>
    <property name="postalcode" type="Integer">
        <column name="postalcode" not-null="true"/>
    </property>
    <properties name="businessKey" unique="true">
        <property name="city"/>
        <property name="postalcode"/>
    </properties>
</class>

Is there a function in the framework to check if the unique key "businessKey" for a given combination is unique (also for single-column unique constraints)?

Maybe in combination of mapping "businessKey" to a class? (Similar to usage of composite-id)

It is just so much redundance to write the code for each table to check its business-key, if it definetly could be done automatic.

Was it helpful?

Solution

there is natural Id which automaticly creates a unique constraint on schema creation and can be used to query for it more efficiently. in xml

<natural-id>
    <property name="name"/>
    <property name="org"/>
</natural-id>

naturalids use the second level cache more efficient and from H4.1 on loading by naturalid uses the first level cache and can save roundtrips. Other than that natural ids are just like normal properties. you could however write a generic natural id checker

  1. create a new object with the properties set
  2. access through the sessionfactory the classmetadata of the object
  3. iterate the natural id properties and use them to get the values from your object and set them on the using(propertyname, propertyvalue)
  4. if something is found copy the data, else just save the object you just created
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top