具有以下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容器初始化阶段。
这意味着什么(这个映射中的外键是什么?什么是主键?哪些注释标记了什么?)以及如何修复它?
发布于 2013-01-05 14:11:45
这种映射没有多大意义。您有一个映射到users_posts_ratings_map
的实体UserPostRating
,并且与实体Post
具有ManyToOne
关联。
在Post
中,您有一组UserPostRating
,但是您将其映射为第二个关联,并使其成为ManyToMany
。它不是ManyToMany
。这是一个OneToMany
,因为另一端是ManyToOne
。由于双向关联已经在UserPostRating
中映射,因此您不能在Post
中第二次映射它。所以代码应该是:
@OneToMany(mappedBy="userPost.post")
private Set<UserPostRating> ratings = new HashSet<>();
发布于 2018-11-28 02:24:28
映射是正确的,因为它是多对多的映射,所以它的映射将导致新的表。因此,您不应该引用现有实体表,而应该提供映射/实体名称不存在的任何其他名称。以下是您的示例:
@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
。
发布于 2013-01-05 14:10:50
根据我怀疑的错误消息,您必须将
@OneToOne
@JoinColumn(name = "ratingId")
private Rating rating;
从类UserPostRating
到类RatingId
。
https://stackoverflow.com/questions/14172401
复制