2

次の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])

サーブレットコンテナの初期化段階。

それはどういう意味ですか(このマッピングの外部キーとは何ですか?主キーとは何ですか?どの注釈が何をマークしていますか?)そしてそれをどのように修正できますか?

4

3 に答える 3

4

このマッピングはあまり意味がありません。エンティティがありUserPostRating、にマップされており、エンティティusers_posts_ratings_mapとのManyToOne関連付けがありますPost

Postは、のセットがありますが、UserPostRatingそれを2番目の関連付けとしてマップし、にしManyToManyます。ではありませんManyToManyOneToMany反対側が。なので、それはですManyToOne。また、双方向アソシエーションはですでにマップされUserPostRatingているため、で2回目にマップすることはできませんPost。したがって、コードは次のようになります。

@OneToMany(mappedBy="userPost.post")
private Set<UserPostRating> ratings = new HashSet<>();
于 2013-01-05T14:11:45.007 に答える
2

多対多のマッピングであるため、マッピングは正しいので、そのマッピングは新しいテーブルになります。したがって、既存のエンティティテーブルを参照するのではなく、マッピング/エンティティ名が存在しない他の名前を指定する必要があります。以下はあなたの例です:

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

"users_posts_ratings_map"名前をまたはなどの他の名前に変更しusers_posts_ratings_map1ますusers_posts_ratings_map_item

于 2018-11-28T02:24:28.490 に答える
1

私が疑うエラーメッセージによると、あなたはの定義を移動する必要があります

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

クラスUserPostRatingからクラスへRatingId

于 2013-01-05T14:10:50.037 に答える