gpt4 book ai didi

java - 具有 MappedSuperclass 字段的同一实体上的多对多

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:30 25 4
gpt4 key购买 nike

我想与双方的同一个表创建ManyToMany关系。它应该代表两个用户之间的友谊。我现在有用户类别:

@Entity
@Table(name = "Users")
public class User extends BaseObject implements UserDetails {

//example of others relationship
private Set<Post> posts;

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true
, mappedBy = "author")
@OrderBy("dateOfCreation DESC")
public Set<Post> getPosts() {
return posts;
}

public void setPosts(Set<Post> posts) {
this.posts = posts;
}
}

@MappedSuperclass

@MappedSuperclass
public class BaseObject {

/** Object id */
private Long id;

@Id
@GeneratedValue
public Long getId() {
return id;
}

public void setId(Long id)
{
this.id = id;
}
}

因为我想向此关系添加一些新列,所以我必须创建将用作连接表的新实体。所以我知道UserFriend:

@Entity
@Table(name = "UserFriends")
public class UserFriend {

/** User */
private User user;
/** User's friend */
private User friend;
/** Pending friendship*/
private boolean accepted;

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

public User getFriend() {
return friend;
}

public void setFriend(User friend) {
this.friend = friend;
}

//other getter setter
}

现在我需要连接这些表。我想使用 user_idfriend_id 指向 User 实体的 id 字段。但我不确定如何实现这一目标。您能给我提示如何使用正确的注释吗?或者给我更好的方法(例如使用新字段用户)。

最佳答案

您可以使用单向 ManyToOne 映射。

/** User */
@ManyToOne
@JoinColumn(name = "user_id")
private User user;

/** User's friend */
@ManyToOne
@JoinColumn(name = "friend_id")
private User friend;

Hibernate 生成表UserFriends,其中包含user_idfriend_id 列。这些列包含由映射父类(super class)的 Id 引用的已连接用户。

对 Hibernate 生成的 DDL 语句的快速验证确认了该功能。

create table UserFriends (id bigint not null, accepted boolean not null, friend_id bigint, user_id bigint, primary key (id))


create table Users (id bigint not null, primary key (id))

关于java - 具有 MappedSuperclass 字段的同一实体上的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com