Given Hibernate 6.4.4 and the following entities:
@Entity
@Getter
@Setter
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@OneToMany(mappedBy = "parentId")
private List<Child> children;
}
@Entity
@Getter
@Setter
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private Long parentId;
}
to my surprise, I can successfully execute a JPQL query like
SELECT p FROM Parent p LEFT JOIN FETCH p.children
or I can load a Parent
entity and lazily load its children by invoking getChildrent()
. Also I can save and update both Parent
and Child
entities independently.
I have the following questions regarding @OneToMany(mappedBy = "parentId")
:
- Is pointing
OneToMany.mappedBy
to a field of a basic type a documented feature? From what I see both Hibernate documentation and JPA specification only describe cases whereOneToMany.mappedBy
references a field with a parent entity type and corresponding@ManyToOne
association. - Are there any pitfalls to this approach, considering that I am not interested in cascade operations?
- What would be the difference between
@OneToMany(mappedBy = "parentId")
and@OneToMany
+@JoinColumn(name = "parent_id")
in this case?