Video in progress

Strong Middle 🐻 Hibernate and JPA

Why does the "object references an unsaved transient instance" error appear when you save while linking a new object to a `@ManyToOne`?

The linked object is transient: it isn't in the database and Hibernate doesn't know it, and no cascade is set. At flush, Hibernate can't find an id for the FK and throws TransientPropertyValueException. If you need to link to a record that's in the database, use getReferenceById(); if it's new, persist() it first.

📖 Answer

The most common case is linking to an existing customer by id:

Order order = new Order();
Customer c = new Customer();
c.setId(dto.customerId());      // we think "I set the id, that's enough"
order.setCustomer(c);
orderRepo.save(order);          // at flush: TransientPropertyValueException

To Hibernate, c is a new, unsaved object: it isn't in the persistence context, and on an entity whose id is generated, an id set by hand means nothing. The right way:

order.setCustomer(customerRepo.getReferenceById(dto.customerId())); // a proxy with no SQL

The proxy is managed and has its id: the FK gets written, and no SELECT goes out to load the customer.

The second case is a genuinely new linked object:

Address a = new Address("Toshkent");
customer.setAddress(a);      // a hasn't been persisted yet

Here either you call em.persist(a) first, or you put cascade = CascadeType.PERSIST on the association. But I'm careful with cascade on a @ManyToOne side: many orders point to one customer, and cascade MERGE/REMOVE there gives unexpected results. Cascade is natural in the parent → child direction (@OneToMany).

In the error text, Hibernate states exactly which entity and which field it is. Read that line first, then work out which case you're in.