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

标签 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 关系映射到列表上外键。

最佳答案

问题是您忘记用@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() { ... } 
}

关于JPA - 外键列表而不是多对多关系中的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097690/

相关文章:

mysql - 当我插入记录时关系表不更新

java - JPA Hibernate 中间表 - 重新提交

entity-framework - 取消删除标记为 EntityState.Delete 的实体?

java - 实体未在数据库中创建表

mysql - 无法将外键添加到我的表

java - 为什么 h2 数据库驱动程序 (JPA) 不创建表,而 postgres 却创建表

mysql - 显示 2 个外键的值

c# - LINQ/lambda : How can I query a DB table based on information from another table?(多对多关系)

java - 使用联接表将 JPA 双向 @ManyToOne 关系映射到多个表

java - Spring Data JPA 创建 bean 时出错