JPA - ManyToMany关系中的外键列表而不是实体列表

时间:2014-08-02 17:35:01

标签: jpa foreign-keys many-to-many joincolumn

我想从现有数据库导入数据,该数据库包含约会表和约会和房间的连接表。

TABLE Appointment {
    id
    ...
}

TABLE Appointment_Room {
    appointment_id,
    room_id
}

我无法访问Room表。

对于我的申请,我有以下约会实体:

@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;
    }
}

由于我只需要与约会相关联的房间的外键值,我希望Appointment的实例包含这些外键的列表。

但是现在我收到以下错误消息:

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)
    ...

我真的不明白造成这个问题的原因,也许有人在那里知道解决方案?

也许使用ORM框架不是这种场景的正确方法,可能还有其他解决方案,但问题似乎很容易让我感到好奇,如果有可能将这个ManyToOne关系映射到列表外键。

1 个答案:

答案 0 :(得分:2)

问题是您忘记使用@ElementCollection注释getRoomIdList()方法,并且JoinColumn不是用于描述必须使用哪些表和列的适当注释。

这是an example显示要做的事情。

@Entity
public class User {
   [...]
   public String getLastname() { ...}

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