2013-01-05 53 views
1

列有一個下面的SQL表:org.hibernate.MappingException:外鍵XXX必須有相同的號碼作爲參照的主鍵YYY

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 
} 

我在servlet容器初始化階段獲得

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

這是什麼意思(什麼是這個映射中的外鍵?什麼是主鍵?哪些註釋標記了什麼?)以及它如何被修復?

回答

3

這種映射沒有多大意義。您有一個實體UserPostRating,映射到users_posts_ratings_map,並與實體PostManyToOne關聯。

而在Post中,您有一組UserPostRating,但將其映射爲第二個關聯,並將其設置爲ManyToMany。這不是ManyToMany。這是一個OneToMany,因爲另一邊是ManyToOne。由於雙向關聯已映射到UserPostRating,因此無法再次將其映射到Post。所以代碼應該是:

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

根據錯誤信息,我懷疑,這必須從UserPostRating類移動的

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

定義RatingId類。

相關問題