我有两张表友谊和用户。我想要做的是与现有用户建立友谊关系。
@Entity(name = "friendship")
public class Friendship {
private static final long serialVersionUID = -8950073132358183472L;
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL})
@JoinColumn(name = "requester_id", referencedColumnName = "id")
private User requester;
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL})
@JoinColumn(name = "receiver_id", referencedColumnName = "id")
private User receiver;
}
@Entity(name = "user")
public class User {
@OneToMany(mappedBy = "requester")
private Set<Friendship> requesterFriendships;
@OneToMany(mappedBy = "receiver")
private Set<Friendship> requestedFriendships;
}
public class FriendshipServiceImpl implements FriendshipService {
@Autowired
FriendshipRepository friendshipRepository;
public Friendship save(Friendship friendship) {
return friendshipRepository.save(friendship);
}
public Friendship requestFriendship(User requester, User receiver) {
Friendship friendship = new Friendship(requester, receiver, LocalDateTime.now(), FriendshipStatus.REQUESTED);
return save(friendship);
}
}
调用控制器方法:
@RequestMapping(value = "/add/{id}", method = RequestMethod.GET)
public String addFriend(@PathVariable("id") long id, Principal principal) {
User requester = userService.getUserByUsername(principal.getName());
User receiver = userService.getUser(id);
if (requester != null && receiver != null) {
friendshipService.requestFriendship(requester, receiver);
}
return "friendsManagement";
}
FriendshipRepository扩展了Spring数据CrudRepository。现在,当我尝试保存时,我收到以下错误。请求者和接收者User对象已经是现有对象。帮我理解这个错误。
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/sample-app] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: uninitialized proxy passed to persist(); nested exception is org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()] with root cause
org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:80)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:757)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:379)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:304)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:146)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:95)