Mappingmedium3-5 years
An entity's `equals`/`hashCode` are generated from its `@GeneratedValue` id. A new `Tag` is added to a `HashSet`, persisted, and then `set.contains(tag)` returns `false` — even though `set.size()` is 1 and iterating returns that exact object. Why, and what should an entity's `equals`/`hashCode` be based on?
Before persist, the id is null, so the hash code is computed from null and the tag is placed in that bucket. persist assigns the id, which changes the hash code, but a HashSet never re-buckets an entry. contains recomputes the hash from the new id, looks in a different bucket, and does not find the object that is still sitting in the old one. Nothing throws, nothing logs. Three implementations work: a real immutable business key (ISBN, email) when one exists; a UUID assigned in the constructor, so the id exists before persist and never changes; or, as a fallback that Hibernate's own documentation suggests, equals on the id with a constant hashCode(), which is always correct but makes lookups in a big hash set linear.
PreviousA service returns an `Order`, and the controller calls `order.getLines()` and gets `LazyInitializationException: could not initialize proxy - no Session`. One teammate suggests making `lines` EAGER; another says just keep `spring.jpa.open-in-view=true`. What is the exception actually telling you, and what is the right fix?Next A `@Transactional` transfer debits one account and then throws a checked `InsufficientFundsException` from a later check. The caller catches it, and the money has moved anyway. Why did the transaction commit, and how do you make it roll back?
Code adds a new `Book` to `author.getBooks()` and persists both. Every assertion in the method passes — `author.getBooks()` contains the book — but in the database `book.author_id` is `NULL`. No error was thrown. What went wrong?`Category.products` is a `@OneToMany(mappedBy = "category")`, and someone adds `orphanRemoval = true` "for consistency" with `Order.lines`, which has it. The next day, an admin un-categorises a product (removes it from the category's collection and clears `product.category`), and the product row is deleted from the database. No `remove()` was called anywhere. Explain the difference between `CascadeType.REMOVE` and `orphanRemoval`, and why only one of them fired here.