Search code examples
javahibernatejpajoincolumn

Hibernate join using non-primary key column


I have two tables:

  1. users:

    • user_id (primary)
    • ip (unique)
    • etc ..
  2. services_to_ip

    • id (primary)
    • service_id
    • ip
    • etc ..

In class User:

@OneToMany()
@JoinColumn(name = "ip", insertable = false, nullable = false, updatable = false)
public List<QPlanService> getPlanServices() {
    return planServices;
}

Using MySQL query log we get something like that:

SELECT *
FROM services_users planservic0_ 
     LEFT OUTER JOIN services qservice1_ 
          ON planservic0_.service_id = qservice1_.id 
WHERE planservic0_.ip = 777

In WHERE condition the 'user_id' field used (the default field is primary key - users.id) (user_id=777).

How can I specify that I need to take the value of the 'ip' field from User entity, not 'user_id'?

I will be grateful for any help!


Solution

  • JoinColumn will only specify the name of the column holding the foreign key, so changing the name of joincolumn absolutely will not help.

    Hibernate will be using the primary key by default for joining, if you want to override this you can simply use referencedColumnName in your relation, but the referenced column should be unique