2

I need to index a column in my SQL DB. There is one way to use a SQL query to create the index on a particular column

CREATE INDEX index_name
ON table_name (column1, column2, ...);

Another way I found on the internet is the use of something like this in JPA

@Table(indexes = @Index(columnList = "firstName"))

Is there any difference between the two? If JPA approach is being followed in real world won't it try to create index each time the project is deployed?

2
  • Hi, Welcome! :-) "Is there any difference between the two?" Sure! the same/no difference as between SQL and JPA... "If JPA approach is being followed in real world won't it try to create index each time the project is deployed?" I guess it relates same/similar as the whole "schema generation" ...but testing is sometimes faster than "knowing/thinking";) (so , it can surely be used in production...but as anything: with care :) Commented Jan 8, 2022 at 2:49
  • @xerx593 Please don't post answers as comments Commented Jan 9, 2022 at 11:15

2 Answers 2

2

Short answer

Use SQL to create/update the schema because it gives more flexibility and maintainability in future migrations, and it is less error-prone.

Long answer:

The @Index annotation is metadata used by the schema generation process to automatically create the database schema.

"If JPA approach is being followed in real world won't it try to create index each time the project is deployed?"

Yes, it will try to create the index and update the schema each time. That is convenient in non-production, but it is bad practice in production.

Sign up to request clarification or add additional context in comments.

Comments

2

For different database indexes creation, SQL queries may vary therefore those SQL queries will be database dependent. For different databases, you may need to write different SQL queries. Whereas @Index is specific to JPA and independent from the database. The same @Index can be used to create an index in a different database.

The @Index will perform its work only while schema generation. In project, we can specify schema generating properties spring.jpa.hibernate.ddl-auto and set to update which is used to update the schema or none in the production.

spring.jpa.hibernate.ddl-auto = update

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.