Home  >  Hibernate

Example of @Index in Hibernate

By Arvind Rai, May 27, 2013
@Index applies the index at property level. If the property of an entity is annotated with @Index, an index with the given name will be applied on the column. Find the example below.

State.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Index;
@Entity
@Table(name = "state")
public class State  implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name = "id")
    private int id;
	
	@Column(name="name")
	@Index(name="nameIndex")
	private String name;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
 }
 


HibernateUtil.java
package com.concretepage.util;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.State;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
		static {
		 try {
				Properties prop= new Properties();
				prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
				prop.setProperty("hibernate.connection.username", "root");
				prop.setProperty("hibernate.connection.password", "");
				prop.setProperty("hibernate.hbm2ddl.auto", "update");
				prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
				
				concreteSessionFactory = new AnnotationConfiguration()
			   .addPackage("com.concretepage.persistence")
					   .addProperties(prop)
					   .addAnnotatedClass(State.class)
					   .buildSessionFactory();
		  } catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		  }
		}
		public static Session getSession()
				throws HibernateException {
			return concreteSessionFactory.openSession();
		}
		
		public static void main(String... args){
			Session session=getSession();
	        session.beginTransaction();
	         State s= new State();
	         s.setId(11);
	         s.setName("Delhi");
	         session.save(s);
	         session.getTransaction().commit();
    	     session.close();
	   }
	}
 
Output
We can see the index applied on the column name

Example of @Index in Hibernate
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS







Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us