gpt4 book ai didi

java - 持久化类在 ID 上给出空值

转载 作者:行者123 更新时间:2023-12-02 00:02:43 28 4
gpt4 key购买 nike

我正在尝试保留一个用户类,其中包含 2 个列表:一个包含用户,用于查看哪些用户关注该特定用户,另一个包含用户,用于查看该特定用户关注哪些用户。

用户.java:

@Entity
@XmlRootElement
@Table(name="Users")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String web;
private String bio;
@OneToMany(cascade=CascadeType.ALL)
private Collection<User> followers = new ArrayList();
@OneToMany(cascade=CascadeType.ALL)
private Collection<User> following = new ArrayList();

我有一个名为UserDAOJPA.java的类,它创建和修改用户:

@Alternative
@Stateless
public class UserDAOJPA implements Serializable, IUserDAO {

@PersistenceContext(unitName = "KwetterSOAPPU")
private EntityManager em;

@Override
public void create(User user) {
em.persist(user);
}
@Override
public List<User> getFollowers(User user) {
List<User> followers;
followers = (List<User>) user.getFollowers();
return followers;
}

@Override
public void addFollower(User user, User follower)
{
user.addFollower(follower);
em.merge(user);
}

@Override
public List<User> getFollowing(User user) {
List<User> following;
following = (List<User>) user.getFollowing();
return following;
}

@Override
public void addFollowing(User user, User following) {
user.addFollower(following);
em.merge(user);
}
@PostConstruct
private void initUsers() {
User u1 = new User("Hans", "http", "geboren 1");
User u2 = new User("Frank", "httpF", "geboren 2");
User u3 = new User("Tom", "httpT", "geboren 3");
User u4 = new User("Sjaak", "httpS", "geboren 4");

this.create(u1);
this.create(u2);
this.create(u3);
this.create(u4);

this.addFollowing(u1, u2);
this.addFollower(u2, u1);
this.addFollowing(u1, u3);
this.addFollower(u3, u1);
this.addFollowing(u1, u4);
this.addFollower(u4, u1);

我自己的猜测是,在查看 User 集合时,我在 User.java 类中缺少正确的注释。

错误信息:

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Column 'FOLLOWING_ID' cannot accept a NULL value.
Error Code: -1
Call: INSERT INTO Users_Users (followers_ID, User_ID) VALUES (?, ?)
bind => [2 parameters bound]
Query: DataModifyQuery(name="followers" sql="INSERT INTO Users_Users (followers_ID, User_ID) VALUES (?, ?)")

最佳答案

用户与其关注者之间的关系是双向多对多关系,而不是两个一对多关系,因此您需要将其映射为这样:

@ManyToMany(mappedBy = "following")
private Collection<User> followers = new ArrayList<>();

@ManyToMany
@JoinTable(name = "followers",
joinColumn = @Column(name = "follower_id"),
inverseJoinColumn = @Column(name = "following_id"))
private Collection<User> following = new ArrayList<>();

另请注意,当引用逻辑上“拥有”的实体时,通常应使用级联。在您的情况下,这是没有意义的,因为用户并不“拥有”彼此。

关于java - 持久化类在 ID 上给出空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499650/

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