Punit Sachan
Punit Sachan

Reputation: 593

Hibernate OneToMany association on other than primary

I am trying to build one to many relationship between two tables using columns other than primary. I want a join between Asset.assetnum and SoftLink.assetnum. I am using hibernate 4 and it always generate relationship between primary.

from ASSET this_ left outer join SOFTLINKS soft3_ on this_.ASSETID=soft3_.ASSETNUM

What I actually want

from ASSET this_ left outer join SOFTLINKS soft3_ on this_.ASSETNUM=soft3_.ASSETNUM

Please suggest if I am missing anything.

@Entity
@Table(name="ASSET")
public class Asset {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ASSETID", nullable = false)
    private int assetid;

    @Column(name="ASSETNUM", nullable = true)
    private String assetnum;    

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "asset") 
    private List<SoftLinks> softlinks = new ArrayList<SoftLinks>(); 
}

@Entity
@Table(name="SOFTLINK")
public class SoftLinks {
    @Id 
    @Column(name="SOFTLINKID", nullable = false)    
    private String softlinkid;

    @Column(name="ASSETNUM", nullable = true)
    private String assetnum;    

    @ManyToOne
    @JoinColumn(name = "ASSETNUM", insertable = false, updatable = false)
    private Asset asset;
}

Upvotes: 2

Views: 81

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154090

In the SoftLinks class you need to change the @ManyToOne association to:

@ManyToOne
@JoinColumn(name = "ASSETNUM", referencedColumnName = "ASSETNUM", insertable = false, updatable = false)
private Asset asset;

Upvotes: 2

Related Questions