Search code examples
javajpamany-to-one

JPA @ManyToOne map multiple fields pointing the same column


I need to map two fields from an entity (in this example, the entity Colectivo), that reference the same column on the related entity TipoDominio. Is it possible?

Colectivo.java

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({@JoinColumn(name = "TDM_TAC", referencedColumnName = "IDETDM")})
private TiposDominioMantenimiento tdmTac;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({@JoinColumn(name = "TDN_ECO", referencedColumnName = "IDETDM")}) 
private TiposDominioMantenimiento tdnEco; 

TipoDominio.java

@Id
@Column(name="IDETDM")
private BigDecimal ideTdm;

If not, how can I specify this? Thanks a lot :)


Solution

  • @JoinColumns should only be used when your related entity has composite/multiple keys.

    So as @crizzis mentioned, a single @JoinColumn should be enough for each attribute.

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TDM_TAC")
    private TiposDominioMantenimiento tdmTac;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TDN_ECO") 
    private TiposDominioMantenimiento tdnEco;