java - 组织.hibernate.MappingException : Foreign key XXX must have same number of columns as the referenced primary key YYY

标签 java hibernate jpa orm hibernate-mapping

有如下 SQL 表:

create table users_posts_ratings_map (
  postId integer not null references posts (id),
  userId integer not null references users (id),
  ratingId integer not null references ratings (id),
  primary key (postId, userId)
);

以及以下 JPA 注释的 POJO:

RatingId.java:

@Embeddable
public class RatingId implements Serializable {
    @ManyToOne
    @JoinColumn(name = "userId")
    private User user;

    @ManyToOne
    @JoinColumn(name = "postId")
    private Post post;

    // getters and setters
}

UserPostRating.java:

@Entity(name = "users_posts_ratings_map")
public class UserPostRating {
    @EmbeddedId
    private RatingId userPost;

    @OneToOne
    @JoinColumn(name = "ratingId")
    private Rating rating;

    // getters and setters
}

Post.java

@Entity(name = "posts")
public class Post {
    @Id
    @Column(nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // irrelevant fields

    @ManyToMany
    @JoinTable(
            name = "users_posts_ratings_map",
            joinColumns = { @JoinColumn(name = "ratingId") },
            inverseJoinColumns = { @JoinColumn(name = "postId"), @JoinColumn(name = "userId") }
    )
    private Set<UserPostRating> ratings = new HashSet<>();

    // getters and setters
}

我得到了

org.hibernate.MappingException: Foreign key (FKB278E73083D94769:users_posts_ratings_map [postId,userId])) must have same number of columns as the referenced primary key (users_posts_ratings_map [ratingId,postId,userId])

在 servlet 容器初始化阶段。

这是什么意思(此映射中的外键是什么?主键是什么?哪些注释标记了什么?)以及如何修复它?

最佳答案

这个映射没有多大意义。您有一个实体 UserPostRating,映射到 users_posts_ratings_map,并且与实体 Post 有一个 ManyToOne 关联。

而在 Post 中,您有一组 UserPostRating,但您将其映射为第二个关联,并将其设为 ManyToMany。它不是 ManyToMany。这是一个OneToMany,因为另一端是一个ManyToOne。由于双向关联已映射到 UserPostRating 中,因此您无法在 Post 中再次映射它。所以代码应该是:

@OneToMany(mappedBy="userPost.post")
private Set<UserPostRating> ratings = new HashSet<>();

关于java - 组织.hibernate.MappingException : Foreign key XXX must have same number of columns as the referenced primary key YYY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172401/

相关文章:

java - 适用于不同语言环境的正则表达式

java - 如何使用Jboss7设置hibernate3?

java - 在 hibernate 中一对多单向添加更多对象到现有列表中

java - JPA1 - ID 是父类(super class)的一部分,由于 @Entity 注释类中缺少 @Id,导致错误

java - Red5-屏幕共享应用程序转换为小程序时屏幕共享屏幕边框模糊

java - 如何限制 JFileChooser 选择特定数量的文件?

java - hibernate Spring 事务

hibernate - 有没有办法基于唯一键而不是主键(在 Hibernate 中)合并 JPA 实体?

java - 如何从 plsql 中的存储过程获取 java 代码中的结果集

java - 为什么在 javaFX AreaChart 中指定 LowerBound 时表单会崩溃?