Search code examples
jpaforeign-keysmany-to-manyjoincolumn

JPA - List of Foreign Keys instead of Entities in ManyToMany relationship


I want to import data from an existing database which contains a table of appointments and a join table for appointments and rooms.

TABLE Appointment {
    id
    ...
}

TABLE Appointment_Room {
    appointment_id,
    room_id
}

I do not have access to the Room table.

For my application I have the following Appointment Entity:

@Entity
public class Appointment {
    private int id;
    ...
    private List<Integer> roomIdList;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    ...

    @JoinColumn (
        table = "Appointment_Room",
        name = "appointment_id",
        referencedColumnName = "id"
    )
    public List<Integer> getRoomIdList() {
        return roomIdList;
    }
    public void setRoomIdList(List<Integer> roomIdList) {
        this.roomIdList = roomIdList;
    }
}

Since I only need the foreign key values of the rooms associated with an appointment, I want that an instance of Appointment contains a list of these foreign keys.

But right now I get the following error message:

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: Appointment_Room, for columns: [org.hibernate.mapping.Column(roomIdList)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:314)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:292)
    at org.hibernate.mapping.Property.isValid(Property.java:239)
    ...

I really don't understand what is causing the problem here, maybe somebody out there knows a solution?

Maybe the use of an ORM framework is not the right approach to this kind of scenario and probably there are other solutions but the problem seems to be so easy that I am curious if there is a possibility to map this ManyToOne relation onto lists of foreign keys.


Solution

  • The problem is that you forgot to annotate your getRoomIdList() method with @ElementCollection, and that JoinColumn is not the appropriate annotation to use to describe which table and columns must be used.

    Here's an example showing hos to do.

    @Entity
    public class User {
       [...]
       public String getLastname() { ...}
    
       @ElementCollection
       @CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id"))
       @Column(name="nickname")
       public Set<String> getNicknames() { ... } 
    }