How to use Hibernate @Index annotation properly?

user597987 picture user597987 · Jul 9, 2011 · Viewed 24.4k times · Source

i have a java class used as an entity that has 2 classes that inherit from it. this class has some indices but these indices didn't appear in the database. this is my java super class code

import java.io.Serializable;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="service", uniqueConstraints = {@UniqueConstraint(columnNames={"name"})})
@org.hibernate.annotations.Table(appliesTo = "service", 
                                 indexes = { @Index(name = "service_name", columnNames = { "name" }), 
                                 @Index(name = "service_description", columnNames = { "description" }),
                                 @Index(name = "service_accessNumber", columnNames = { "access_number" })   
                     })
public class Service implements Serializable {

@Column(name="access_number",length = 95,nullable=false)
    String accessNumber;

@Column(length=80,nullable=false)
    String name;

@Column(length=140)
    String description;

}

does any one know what is my problem Note: i have this problem in my all java classes but this is one of them. the code in all class is the same of this

Edit: i build an xml file and put it in a grails project, and when i run this project, database created

Answer

Xiè Jìléi picture Xiè Jìléi · Jul 13, 2011

Would a single @Table annotation work? I haven't tried it, I guess the Hibernate @Table might be overridden by JPA @Table.

You may also try @Index annotation on the column fields:

public class Service implements Serializable {
    @Index(name="service_accessnumber")
    @Column(name="access_number",length = 95,nullable=false)
    String accessNumber;

    @Index(name="service_name")
    @Column(length=80,nullable=false)
    String name;

    @Index(name="service_description")
    @Column(length=140)
    String description;
}