Hibernate / Hibernate 7 Basics Interview Questions
How do you map one-to-many and many-to-one relationships in Hibernate 7?
Relationships are mapped using @OneToMany, @ManyToOne, etc. The owning side holds the foreign key column.
@Entity public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; @OneToMany( mappedBy="customer", cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.LAZY ) private List<Order> orders = new ArrayList<>(); public void addOrder(Order o) { orders.add(o); o.setCustomer(this); // keep both sides in sync! } } @Entity @Table(name="orders") public class Order { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private BigDecimal total; @ManyToOne(fetch=FetchType.LAZY) // explicit LAZY recommended @JoinColumn(name="customer_id", nullable=false) private Customer customer; // owning side: holds FK } // Usage: Customer c = new Customer("Alice"); c.addOrder(new Order(new BigDecimal("50"))); session.persist(c); // cascades to orders
In a bidirectional @OneToMany/@ManyToOne relationship, which side holds the FK column?
What does CascadeType.ALL on @OneToMany mean?
More Related questions...