I am trying to implement a jpa query method from a key field defined as a JoinColumn for a ManyToOne relationship.
This is part of an application I'm working, built with Maven using Spring 5 and Jpa 2.1 versions.
Expected behavior of schema: "A" entity (primary key =a_id) must be owned by "B" entity (primary key= b_id), where B can own more than one entries in A. From the perspective of database, I need to store the foreign key b_id in A entity, but not the other way around.
class A {
@id
Long a_id;
@ManyToOne(optional = false)
B b;
}
class B {
@id
Long b_id;
@OneToMany(mappedBy = "b_id", cascade = CascadeType.ALL)
@Transient
private Set<Jobs> jobs;
}
//Are there any corrections or simplifications I can make to this model?
//Now I’m trying to extract all A entries, which have a specific b_id //using query methods
ARepository extends JpaRepository<A, Long> {
Optional<List<A>> findByB_id(Long B_id);
}
This is error I get with this approach:
Error: Unable to locate Attribute with the the given name [B_id] on this ManagedType [<package_path>.A]
mappedBy
references the inverse relationship which is in your example b
not b_id
.
So change
@OneToMany(mappedBy = "b_id", cascade = CascadeType.ALL)
to
@OneToMany(mappedBy = "b", cascade = CascadeType.ALL)