JPA问题@OneToMany – 如何从数据库中获取特定对象?

huangapple go评论102阅读模式
英文:

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

问题

我有UserSeries实体。一个用户拥有一系列列表。

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 = &quot;user_id&quot;)
    private List&lt;Series&gt; series = new ArrayList&lt;&gt;();
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name=&quot;series&quot;)
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&lt;Series&gt; 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&lt;Series&gt; getSeriesByUserId(int userId) {
   return seriesRepository.findByUserId(userId);
}

huangapple
  • 本文由 发表于 2020年8月24日 00:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63549133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定