Relationships and mapping
27 questions in 8 subtopics.
One-to-many and many-to-one
Map a bidirectional Order toOrderLine relationship correctly, and write helper methods that keep both sides in sync.A unidirectional @OneToMany private List<OrderLine> lines on Order (no mappedBy, no @JoinColumn) produces an extra table order_lines and several statements per insert. Why?A Customer has hundreds of thousands of Orders. Should Customer have a @OneToMany collection of orders? Explain your reasoning.Many-to-many
Why is a Set usually preferred over a List for a@ManyToMany association in Hibernate, and when should you replace @ManyToMany with an explicit join entity?Removing one tag from a post (post.getTags().remove(tag)) produces DELETE FROM post_tag WHERE post_id = ? followed by 49 INSERT statements. What is the cause and the fix?Your domain has users, groups and permissions with many-to-many links that are queried in authorization checks on every request. How would you design the model and its access patterns?Your core relational schema was designed fifteen years ago around many-to-many relationships between customers, accounts and products, and every new product needs schema changes. How do you evaluate a redesign of the data model against the cost of living with it?Owning side and mappedBy
A developer adds a line withorder.getLines().add(line) but never calls line.setOrder(order). After commit, the order_id column of the new line is null. Why?For a bidirectional @OneToOne between User and UserProfile, which side should own the relationship and how does that choice affect lazy loading?Your company's core domain model maps hundreds of JPA entities with deep bidirectional relationships across modules owned by different teams. Over the years, every change ripples across teams. What long-term structural changes would you push for?Cascade and orphanRemoval
What is the difference betweenCascadeType.REMOVE and orphanRemoval = true on a @OneToMany collection?This code throws 'A collection with cascade=all-delete-orphan was no longer referenced by the owning entity instance': order.setLines(new ArrayList<>(newLines)). Why, and how do you fix it?Deleting a Customer with CascadeType.ALL on orders, and orders cascading to lines and payments, takes minutes and sometimes times out. What happens and what would you do?Inheritance mapping strategies
CompareSINGLE_TABLE, JOINED and TABLE_PER_CLASS inheritance strategies and @MappedSuperclass.You must model payments that can be card, bank transfer or wallet, with 5 shared fields and 3 to 8 type-specific fields each. Most queries list payments of all types for an account. Which mapping would you choose?A core entity hierarchy mapped with JOINED inheritance across 12 subclasses now dominates database CPU through wide joins. Changing it affects 6 teams. How would you lead the change?Object-relational mapping encourages modelling the database around class hierarchies. After years of experience with inheritance-heavy JPA models, what modelling principles would you set for long-lived systems?Embeddables
Map a Customer with a home Address and a billing Address, both using the same@Embeddable class, stored as columns of the customer table.An entity has @ElementCollection List<PhoneNumber> phones. Every update to one phone number deletes all rows and re-inserts them. Why, and when is @ElementCollection a poor choice?Teams model money, addresses and date ranges in different ways across entities (separate columns, strings, JSON). How would you standardise value objects in JPA models across services?Equals and hashCode for entities
An entity uses Lombok@Data and has a bidirectional @OneToMany. Calling toString() or adding it to a HashSet causes a StackOverflowError or loads the whole database. Explain and give a safe approach.Write equals and hashCode for an entity with a database-generated Long id so that it works in HashSets before and after persist and with Hibernate proxies.Set a team-wide convention for entity identity, equality and identifiers so that collection bugs and proxy issues stop recurring. What would it contain?Identity bugs (entity equality, duplicated records, merged customers) have caused long-running data quality problems in your company. What long-term identity strategy would you set for business entities across systems?One-to-one mapping
Map a User andUserProfile one-to-one so the profile table shares the user's primary key, using @OneToOne with @MapsId. Why is this better than a separate profile_id foreign key, and why may @OneToOne(fetch = LAZY) on the non-owning side still load eagerly?Loading 100 Order entities runs 101 extra queries, one per order for its Invoice, although Invoice is mapped @OneToOne(mappedBy = "order", fetch = FetchType.LAZY) on Order. Explain why, and give three fixes with their trade-offs.A Customer table has grown to 120 columns because every feature added fields; some are large and rarely read. A team proposes splitting into several one-to-one tables (customer_core, customer_preferences, customer_kyc). How would you evaluate and do this safely?No question matches these choices.