Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiple column UniqueConstraint in hbm?

Working on some legacy hibernate code.

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

@Table(name="users", uniqueConstraints = {     @UniqueConstraint(columnNames={"username", "client"}),     @UniqueConstraint(columnNames={"email", "client"}) }) public class User implements Serializable {     private static final long serialVersionUID = 1L;     @Id     private int id;     private String username;     private String email;     private Client client; } 
like image 599
Gabriel Avatar asked Apr 29 '10 22:04

Gabriel


2 Answers

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.

like image 67
Thierry Avatar answered Sep 30 '22 21:09

Thierry


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.

like image 31
Shayan Mirzaee Avatar answered Sep 30 '22 19:09

Shayan Mirzaee