In hibernate we can use @Index to create index. eg @Index(name = “indexed_name”)
@Entity
@Table(name = "book_info")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "book_id")
@Index(name = "BOOK_ID_IDX")
private String bookId;
}
You can also define multiple index using same annotation.
@Entity
@Table(name = "book_info")
indexes = {
@Index(name = “IDX_BOOK_CODE”, columnList = bookCode, unique = false),
@Index(name = “IDX_BOOK_ID”, columnList = bookid, unique = false)}
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "book_code")
private String bookCode;
@Column(name = "book_id")
private String bookId;
}
Creating Unique Key Constraints
@uniqueConstraints used to create unique key constraints in hibernate java, we can create unique key on single column and on multiple column as well.
@Entity
@Table(name = "book_info")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(unique = true)
@Column(name = "book_code")
private String bookCode;
@Column(name = "book_id")
private String bookId;
}
Or we can create in another way
@Entity
@Table(name = "book_info")
uniqueConstraints={
@UniqueConstraint(name=”PK_BOOK_ID_AND_CODE”,columnNames={bookId,bookCode}),
}
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(unique = true)
@Column(name = "book_code")
private String bookCode;
@Column(name = "book_id")
private String bookId;
}