英文:
JPA problem @OneToMany - how to get particular objects from database?
问题
我有User
和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; //作为 URL
private String description;
private float totalScore;
private float score;
User user;
}
我想获取分配给特定用户的系列。
在系列服务中,我像这样获取系列:
@Override
public List<Series> getAllSeries() {
return seriesRepository.findAll();
}
但是我从数据库中获取了所有系列。有人能告诉我我做错了什么吗?我是否应该在请求中传递用户?
英文:
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
得分: 3
你正在获取 series,因为你查询了 Series 仓库,使用 findAll() 方法。
如果你想获取属于特定用户的 Series,只需将 userId 传递给相应的方法,例如:
@Override
public List<Series> getSeriesByUserId(int userId) {
return seriesRepository.findByUserId(userId);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论