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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
