JPA problem @OneToMany - how to get particular objects from database?

Viewed 54

I have User and Series entities. An user has list of series.

public class User {

    @Id
    @GeneratedValue
    private int id;

    private String userName;
    private String password;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "user_id")
    private List<Series> series = new ArrayList<>();
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="series")
public class Series {

    @Id
    @GeneratedValue
    private int id;

    private String name;
    private String year;
    private String photo; //as an url
    private String description;
    private float totalScore;
    private float score;

    User user;
}

I want to get series which are assign to particular user. In the Series service, I do something like this to get series:

@Override
public List<Series> getAllSeries() {
    return seriesRepository.findAll();
}

But I get all series from database. Could someone tell me what I'm doing wrong? Should I pass the user in the request?

1 Answers

You are getting series, because you query the Series Repository, with findAll().

If you want to get Series, which belong to the particular user, just pass the userId to the corresponding method, like:

@Override
public List<Series> getSeriesByUserId(int userId) {
   return seriesRepository.findByUserId(userId);
}
Related