When i want to get data using @ManyToMany() annotation, i get empty array as response, when using mappedBy on second side of relationship

39 views Asked by At

I created User and Course entities. While both are in one to many relationship as one user is a creator of many courses, then i also added many to many relationship as one user can by many courses and one course can be bought by many users. When I implemented many to many relationship using in User entity @ManyToMany and @JoinTable and in Course @ManyToMany(mappedBy ="..."), when want to get all courses owned(bought) by user, i got empty array even when I there is a record in join table that says he has one course. This are my entites implementations:

User

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Table(name = "user")
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer iduser;
    private String firstname;
    private String lastname;

    private String email;
    @JsonIgnore
    private String password;

    @Enumerated(EnumType.STRING)
    private EUserType type;

    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
    @JoinTable(name = "ownership_test", joinColumns = @JoinColumn(name = "user_iduser", referencedColumnName = "iduser"), inverseJoinColumns = @JoinColumn(name = "course_idcourse", referencedColumnName = "idcourse"))
    private Set<Course> courses;

    public void buyNewCourse(Course course) {
        this.courses.add(course);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of(new SimpleGrantedAuthority(type.name()));
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Course

@Entity
@Table(name = "course")
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class Course {
    @Id()
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer idcourse;
    private String name;
    @Column(precision = 10, scale = 2)
    private BigDecimal cost;
    @ManyToOne
    @JoinColumn(name = "category_idcategory", referencedColumnName = "idcategory")
    private Category category;
    @ManyToOne
    @JoinColumn(name = "user_iduser", referencedColumnName = "iduser")
    private User creator;
    @ManyToMany(mappedBy = "courses", fetch = FetchType.LAZY)
    Set<User> owners;

}

UserService


@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final ModelMapper modelMapper;

    public Set<Course> getCurrentUserOwnedCourses(String email, Pageable pageable)
            throws NotFoundException {
        return userRepository.findByEmail(email).orElseThrow(() -> new NotFoundException("User not found"))
                .getCourses();
    }
}

UserController

@RestController
@RequestMapping(value = "/users")
@RequiredArgsConstructor
@Validated
public class UserController {
    private final UserService userService;

    @GetMapping(value = "/me/courses")
    public ResponseEntity<?> getCurrentUserOwnedCourses(Principal principal, Pageable pageable)
            throws NotFoundException {
        return new ResponseEntity<>(userService.getCurrentUserOwnedCourses(principal.getName(), pageable),
                HttpStatus.OK);
    }
}

When i deleted @ManyToMany(mappedBy = "courses") from Course Entity, getting courses work as excpected. I am really interested why it don't work using bidirectional relationship.

Thank you for any help.

0

There are 0 answers