Video in progress
Can you map a single FK column both as a `@ManyToOne` association and as a plain `Long customerId` field?
You can, but one of the two has to be read-only: usually @Column(insertable = false, updatable = false). Otherwise Hibernate fails at startup with a "column is duplicated in mapping" error. The read-only field is filled only on load: after persist() it stays null.
📖 Answer
@Entity
class Order {
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "customer_id")
private Customer customer;
@Column(name = "customer_id", insertable = false, updatable = false)
private Long customerId;
}
What it's for: working without touching the association where you need only the id (where o.customerId = :id, a DTO, a log line), and comparing against an id that came from another service.
It matters which side is the "writer". In the variant above, customer controls the column. The reverse is possible too: customerId is written, and @JoinColumn(insertable = false, updatable = false) goes on customer. That's sometimes convenient: you supply only the id for the association without loading the entity. But then the customer field isn't filled automatically for a new object.
The trap is keeping them in sync:
Order o = new Order();
o.setCustomer(em.getReference(Customer.class, 7L));
em.persist(o);
o.getCustomerId(); // null! Hibernate doesn't fill the read-only field
The value appears only when the entity is re-read from the database (refresh, a new transaction). That's why I leave such a field without a setter and document it.
In most cases you don't need this second field at all: order.getCustomer().getId() doesn't produce SQL on a lazy proxy.
Sign up to mark studied questions and save your progress.