Video in progress

Strong Junior 🐻 Hibernate and JPA

How is field access versus property access chosen for an entity, and why does it matter where you put `@Id`?

Hibernate determines the access type from where @Id is placed: on a field means field access, on a getter means property access. The other annotations must sit in the matching place, otherwise they are silently ignored.

📖 Answer

@Entity
class Product {
    @Id @GeneratedValue
    private Long id;            // field access

    private String name;

    @Column(name = "price_uzs") // works: it's on the field
    private long price;

    @Transient
    public String getLabel() { return name + " " + price; }
}

With field access, Hibernate reads and writes the fields directly through reflection and doesn't call the getters. So even if you put logic in a getter (formatting, lazy computation), it doesn't affect the database. Most teams choose this variant.

With property access (@Id on the getter), Hibernate works through the getters and setters. There, a @Column on a field is not taken into account, and this is where the question "I added the annotation but it doesn't work" comes from.

If you need to mix them, you can choose separately for one attribute with @Access(AccessType.PROPERTY), but I rarely do that.