The answer could be quite different based on what you are looking for.
Based on your current mapping, assuming you have a Primary
instance on hand, you can get its corresponding Secondary
by querying. E.g. by HQL:
from Secondary s where s.primary = :primary
and pass in your primary as the parameter.
If you are looking for way to navigate from a Primary
object instance, you could have created a bi-directional mapping:
class Primary {
@OneToMany(mappedBy="primary", ...)
private Set<Secondary> secondaries;
}
class Secondary {
@ManyToOne
private Primary primary;
}
You could refer to my (very old) answer on related question on how to define it. https://stackoverflow.com/a/13812047/395202
However, simply having a bi-directional relationship DOES NOT avoid "selecting twice", if your "selecting twice" means running 2 SQL queries in DB.
To reduce such round-trip, there are several way to solve. First one is to declare the relationship as EAGER fetch. However this is a way that I don't usually recommend so I won't go deeper.
Another (imho, more appropriate) way is to do a join fetch when you are fetching Primary
. To fetch the Primary
instance with its related Secondary
instances, use a HQL like :
from Primary p left join fetch p.secondaries where ....