Sitemap
chanthirakumar chayanthithan

chanthirakumar chayanthithan

2 min readMar 24, 2025

--

Press enter or click to view image in full size

Indexing

Indexing refers to optimizing database queries by creating indexes on specific columns to speed up searches.

Using JPA Indexing - If your application only deals with structured data (e.g., IDs, numbers, relationships), JPA indexing is sufficient

The steps that you have to

Step1 - Define Indexes in JPA Entity

Get chanthirakumar chayanthithan’s stories in your inbox

Join Medium for free to get updates from this writer.

JPA provides the @Index annotation inside the @Table annotation to specify indexes.

@Data
@Entity
@XmlRootElement
@Table(
name = "user",
indexes = {
@Index(name = "idx_user_id",columnList = "user_id"),
@Index(name = "idx_user_email",columnList = "user_email"),
@Index(name = "idx_user_email_v2fa",columnList = "user_email,v2fa"),

}
)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "user_id")
private Long userId;
@Column(name = "first_name")
private String firstName;
@Column(name = "user_email")
private String userEmail;
@Column(name = "user_password")
private String userPassword;
@Column(name = "is_approved")
private Boolean isApproved;
@Column(name = "is_active")
private Boolean isActive;
@Column(name = "last_name")
private String lastName;
@Column(name = "is_verify")
private Boolean isVerify;
@Column(name = "company_name")
private String companyName;
@Column(name = "nature_purpose")
private String naturePurpose;
@Column(name = "v2fa")
private String v2fa;

}

Step2 — Manually add indexes in Flyway migration

V6__Add_Index_To_User.sql

CREATE INDEX idx_user_id ON user (user_id);
CREATE INDEX idx_user_email ON user (user_email);
CREATE INDEX idx_user_email_v2fa ON user (user_email,v2fa);

Step 3 — Configure Flyway in Spring Boot

spring.flyway.enabled = false
spring.flyway.locations = classpath:db/migration
spring.flyway.baseline-on-migrate = true

Step4 - Verify indexes in database

Step5 — Test performance improvement

EXPLAIN ANALYZE SELECT * FROM users WHERE user_id= '6246839njf';

Using JPA Indexing + Elasticsearch Together — If your application requires fast searching, filtering, and full-text search, adding Elasticsearch can enhance performance.

Press enter or click to view image in full size
Press enter or click to view image in full size

--

--