gpt4 book ai didi

java - 如何将两个ID插入链接两个用户的表中?

转载 作者:行者123 更新时间:2023-11-30 01:41:56 25 4
gpt4 key购买 nike

我想建立一个关注机制,我有以下 User 类,它也是 friend 类:

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USER_ID")
private Long id;

private String firstName;

private String lastName;

private String username;

private String password;

@Column(unique = true)
private String email;

@Column(unique = true)
private String phoneNumber;

private int age;

private Role role;

@OneToMany(mappedBy = "shareId")
private List<Share> shares;

@OneToMany(mappedBy = "trackId")
private List<Track> tracks;

//number of days of cooldown
private int cooldown;

private long numberOfReports;

@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="FRIENDS",
joinColumns={@JoinColumn(name="USER_ID")},
inverseJoinColumns={@JoinColumn(name="FRIEND_ID")})
private Set<User> friends = new HashSet<User>();

@ManyToMany(mappedBy="friends")
private Set<User> befriended = new HashSet<User>();

这段代码自动创建一个名为friends的表,其中包含用户user_id和friend_id之间的链接,现在当我想在用户之间创建链接时,如何告诉Hibernate这样做?用户服务:

        User followerUser = userRepository.findByUsername(followerUsername);
User followedUser = userRepository.findByUsername(followedUsername);
return userRepository.SOMETHING(followerUser.getId(), followedUser.getId);
}

userRepository 中的方法应该是什么样的?

最佳答案

您应该能够通过更新用户并使用 save 来做到这一点,例如:

followerUser.getFriends().add(followedUser);
// This is not necessary for database, but useful on object level
followedUser.getBefriended().add(followerUser);

userRepository.save(followerUser);

关于java - 如何将两个ID插入链接两个用户的表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59636173/

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