Pages

Monday, March 16, 2015

Hibernate: Unique constraint on multiple column names in Java

In Hibernate ORM, we can define Data Definition Language (DDL) to create unique key based on multiple columns.

Suppose, we have a system where users can import email addresses from gmail or other email services and can send joining invitation to our site.

We can save these email addresses in a database.


  • Please note a user can save same email address  in his different contact lists (e.g. both of his gmail and yahoo contact lists are containing a friend's email address )
  • Again multiple user can have the same email address in their contact lists.


In the above cases, we need to save an email address against a single user. It means we need to make unique constraint based on 2 fields

  • email
  • importing user
In Java, we shall use the following annotations:

  • @Table and
  • @UniqueConstraint


Below is a sample code depicting the usage of the annotations:


import javax.persistence.Table;// For @Table annotation
import javax.persistence.UniqueConstraint;// For @UniqueConstraint annotation

@Table(uniqueConstraints= @UniqueConstraint(columnNames = {"email", "importer"}) )
public class ImportedContact {
        @Column(nullable = false)
 private String email;
 
 @Column(nullable = false, columnDefinition = "TINYINT(1) default 0")
// @Type(type="org.hibernate.type.NumericBooleanType")
 private boolean isInvited;
 
 @ManyToOne(optional = false)
 @JoinColumn(name="importer")
 private EUser importer;
 


Please Note our importer is in @ManyToOne relationship.

In that case we can not just use importer property as columnNames field list.

We need to use @JoinColumn annotation to put a string name to that field.

The @JoinColumn property name need to be used in columnNames list.


Please Note the way of using MySQL TinyInt datatype in Hibernate and Java used in our example for the column name:  isInvited along with a default value.

No comments :

Post a Comment