Quick revision
The short answer
For composite keys we use @EmbeddedId with an @Embeddable key class, or @IdClass, and the key class must implement equals and hashCode. Column names in a different convention are handled with @Column(name = ...) or a PhysicalNamingStrategy applied to everything. Tables without a primary key cannot be mapped as entities safely, so we add a key or read them through views and native queries. We decide to map only what the service needs, and use ddl-auto=validate to prove the mappings match the schema.
What to remember
In this answer, we mapped a legacy schema with JPA. Composite keys use @EmbeddedId with an @Embeddable key, or @IdClass, and the key class needs equals and hashCode so the persistence context can find entities by id. Naming differences are handled with @Column and @Table for exceptions or a PhysicalNamingStrategy for the whole schema, remembering Boot's default underscore strategy. Tables without a primary key are not mapped as entities unless we add a key; otherwise we read them through views or DTO queries and write with explicit SQL. We map only what the service needs, and ddl-auto=validate in a test against the real schema proves the mapping.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For composite keys we use @EmbeddedId with an @Embeddable key class, or @IdClass, and the key class must implement equals and hashCode. Column names in a different convention are handled with @Column(name = ...) or a PhysicalNamingStrategy applied to everything. Tables without a primary key cannot be mapped as entities safely, so we add a key or read them through views and native queries. We decide to map only what the service needs, and use ddl-auto=validate to prove the mappings match the schema.
Why this question is asked
Most JPA examples start with a clean schema designed for JPA: a surrogate id on every table and names that follow Java conventions. Legacy databases are different. They were designed years ago, often for another language, and they are shared with other systems that cannot change. Interviewers ask this design question to see whether we can make JPA fit the schema we have instead of the one we wish we had, and whether we know when JPA is the wrong tool for a table. In this answer, we will go through composite keys, naming, tables without keys, deciding how much to map, and validation.
1Composite Primary Keys With @EmbeddedId
A composite primary key is a key made of several columns together, such as order_no plus line_no for an order line. JPA needs one Java object to represent the id, so we create a key class holding both values. The cleanest option is an @Embeddable key used with @EmbeddedId.
The key class must implement equals and hashCode based on all key fields. The reason is the persistence context: Hibernate stores managed entities in a map keyed by id, so two key objects with the same values must be equal, or find would miss an entity that is already loaded, and the same row could end up as two different objects. The specification also requires the key class to be Serializable and to have a no-argument constructor.
The alternative, @IdClass, keeps the key fields directly on the entity, each marked @Id, and names a separate class with the same fields as the id type. It reads more naturally in queries (o.orderNo rather than o.id.orderNo) and is common when part of the key is also a foreign key. Both work; consistency across the service matters more than the choice.
2Columns in a Different Naming Convention
Legacy names such as T_ORD_LINE, ORD_NO or CUSTNAME rarely match Java fields. For a few exceptions, @Table(name = ...) and @Column(name = ...) on each attribute are clear and explicit. When the whole schema follows a different rule, a naming strategy is better.
Hibernate separates two steps. The implicit naming strategy decides a logical name when we do not give one, and the physical naming strategy turns every logical name into the actual database name. Spring Boot sets CamelCaseToUnderscoresNamingStrategy as the physical strategy by default, which turns customerName into customer_name. If our legacy schema uses explicit names that must be used exactly as written, we switch to PhysicalNamingStrategyStandardImpl, which leaves names alone. If it follows a consistent rule, such as a T_ prefix on tables, a small custom PhysicalNamingStrategy can apply it.
Notice how important this choice is: with the default strategy, @Column(name = "custName") becomes cust_name, which surprises many developers working with legacy schemas.
3Tables Without a Primary Key
Hibernate identifies every entity by its id. It uses the id to keep one object per row in the persistence context and to target UPDATE and DELETE statements. A table with no primary key gives it nothing reliable to use. If we pretend some column is the id when it is not unique, Hibernate will return the same object for different rows, or update several rows when we meant one, without any error.
So we have three honest options. The best is to add a key: a surrogate id column with a sequence, if the other systems that use the table can tolerate a new column. If we cannot change the table, and we only read it, we map a view or a query instead of an entity: a native query or JdbcClient returning a DTO record, or an entity marked @Immutable over a view whose chosen columns really are unique together, so Hibernate never writes. If we must write to it, we do so with plain SQL that states its own WHERE clause.
- Does it have a unique key?YesMap as an entity (@Id or @EmbeddedId)NoContinue
- Can we add a surrogate key column?YesAdd it, then map as an entityNoContinue
- Does the service only read it?YesView, @Immutable entity or DTO queryNoWrite with explicit SQL via JdbcClient
3 steps in order. Play them, or step through them one at a time.
Never invent an @Id from columns that are not truly unique.
4Map Only What the Service Needs
A legacy schema may have 300 tables, and our service may need 15 of them. Mapping everything is tempting for completeness, but each mapped table is code to maintain and test, and every mapped association is a chance for accidental lazy loading of half the database. So we decide deliberately: map the tables the service reads and writes, with the columns it uses, and leave the rest out. Associations to tables we do not otherwise use can often be replaced by a plain foreign key column.
This also makes ownership clearer. If other systems write to the same tables, our mappings should be conservative: mark columns we must never change as insertable = false, updatable = false, so a careless setter cannot overwrite data owned by another system.
5Proving the Mapping With ddl-auto=validate
With a hand-written mapping over a schema we did not design, mistakes are likely: a wrong column name, a numeric type mapped to the wrong Java type, a missing table. Setting spring.jpa.hibernate.ddl-auto=validate makes Hibernate compare every mapped entity with the real schema at startup, and fail if a table or column is missing or a type does not match. It never changes the schema.
We run this in an integration test against a copy of the legacy schema in Testcontainers, built from the same DDL the production database has. Then every mapping change is checked on every build, before it ever meets production.
6Follow-up questions
Can a composite key include a foreign key to another entity?
Yes. With @EmbeddedId we add @MapsId("orderNo") on the @ManyToOne to the parent, so the association and the key field share the same column. With @IdClass we can put @Id directly on the @ManyToOne. Both let us navigate to the parent while keeping the composite key.
Should a composite key class be a record?
Recent Hibernate versions support records as embeddable id classes, and records give correct equals and hashCode automatically, which removes a common bug. Check your Hibernate version first; on older versions, a regular class with hand-written equals and hashCode is the safe choice.
7Conclusion
In this answer, we mapped a legacy schema with JPA. Composite keys use @EmbeddedId with an @Embeddable key, or @IdClass, and the key class needs equals and hashCode so the persistence context can find entities by id. Naming differences are handled with @Column and @Table for exceptions or a PhysicalNamingStrategy for the whole schema, remembering Boot's default underscore strategy. Tables without a primary key are not mapped as entities unless we add a key; otherwise we read them through views or DTO queries and write with explicit SQL. We map only what the service needs, and ddl-auto=validate in a test against the real schema proves the mapping.
Open with
For composite keys, I would use @EmbeddedId with an @Embeddable key class holding the key columns, or @IdClass if I want the key fields directly on the entity, for example when part of the key is a foreign key.
Then, if they want more
Either way the key class must implement equals and hashCode over all key fields, be Serializable and have a no-arg constructor, because Hibernate looks entities up by id in the persistence context. For naming, a few odd names get @Table and @Column, but for a whole schema in another convention I would set a physical naming strategy.
Spring Boot's default turns camel case into underscores, which surprises people with legacy names, so often I switch to PhysicalNamingStrategyStandardImpl and use exact names, or write a small custom strategy for a consistent prefix rule.
Tables with no primary key I would not map as entities with a fake id, because Hibernate relies on the id for identity and for targeting updates. I would add a surrogate key if possible; otherwise read the table through a view, an @Immutable entity over truly unique columns, or a DTO query, and write with explicit SQL.
I would map only the tables and columns the service needs, mark columns owned by other systems as not insertable or updatable, and run ddl-auto validate in an integration test against the real schema so every mismatch fails the build.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You are mapping a legacy schema with composite primary keys, columns named in a...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/fe7ad70b87/