I have created the Friends table which have self join ManyToMany relation. Friends entity have List of Friends which result as third table for representing the ManyToMany relation.
public class Friends {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany
@JoinTable(
name = "friends_list",
joinColumns = @JoinColumn(name = "friends_from"),
inverseJoinColumns = @JoinColumn(name = "friends_to"))
private List<Friends> friends;
}
I want to create a query on joined table. I have created Query like
@Query(value="Select * from friends_list f where f.friends_from=:id", nativeQuery=true)
public List<Friends> findFriendsById(@Param("id") Long id);
Now, It throws the below error when I raise request of creating the resource.
@RestController
public class FriendsController {
@Autowired
private FriendsService friendsService;
@PostMapping("/friends")
public Friends createFriends(@RequestBody Friends frnd)
{
return friendsService.createFriends(frnd);
}
@GetMapping("/friends/{id}/distance/{k}")
public List<Friends> getFriendsAtDistanceK(@PathVariable("id") Long id,@PathVariable("k") int k)
{
return friendsService.getFriendsAtDistanceK(id, k);
}
}
Request
{
"id":1,
"name":"sujeet",
"friends":[
{
"friends_from":1,
"friends_to":2
}
]
}
I have already created two friends without list of friends. And I am trying to add friends with list of friends. But it is showing below error.
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.learn.friends.entity.Friends
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:347) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]
CodePudding user response:
Have you tried using @Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
annotation for this? The source to this solution is here