1
public class Primary{
    private long id;
    @Id
    @GeneratedValue(
        strategy = GenerationType.IDENTITY
    )
    @Column(
        name = "id"
    )
    public void getId(){return id;}

    //other vars
}

public class Secondary{
    //other vars
    private Primary primary;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "primary_id", unique = true)
    public Primary getPrimary(){return primary;}
}

From this, it is pretty easy to get a Primary Object from a Secondary Object. However, how do I get Secondary Object from a Primary Object without selecting twice in Hibernate?

theAnonymous
  • 1,701
  • 2
  • 28
  • 62

3 Answers3

1

The Primary class should look like this:

@OneToMany(mappedBy="primary", cascade={CascadeType.ALL})
private List<Secondary> secondaries;
// getter and setter

And you should make a small modification in Secondary:

@JoinColumn(name = "id", unique = true)
public Primary getPrimary(){return primary;}

Cause join column should refer to the joined field(id) in Primary.

Dave Pateral
  • 1,415
  • 1
  • 14
  • 21
1

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 ....
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
0

Add this Setter method in the Secondary Class

public Primary getPrimary() {
        return primary;
    }

And get the primary object from Secondary Class

Arul Suju
  • 706
  • 1
  • 9
  • 21