spring data jpa如何过滤子对象?

还未解决,我在stackoverflow上https://stackoverflow.com/que... 找到了个类似问题,我亲自试了一下,发现并不能过滤子结果集,只能过滤parent,过滤后的parent带出来的还是全部子对象,

@Entity
public class Player {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @OneToMany(mappedBy = "player")
    private List<PlayerItem> playerItems;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<PlayerItem> getPlayerItems() {
        return playerItems;
    }

    public void setPlayerItems(List<PlayerItem> playerItems) {
        this.playerItems = playerItems;
    }
}

@Entity
public class PlayerItem {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private Boolean begin;

    @ManyToOne
    @JoinColumn(name = "play_id")
    @JsonIgnore
    private Player player;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean getBegin() {
        return begin;
    }

    public void setBegin(Boolean begin) {
        this.begin = begin;
    }

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }
}

public interface PlayerRepository extends JpaRepository<Player, Integer> {
    List<Player> findByPlayerItemsName(String name);
}

@RestController
public class TestQcController {
    @Resource
    PlayerRepository repository;

    @PostMapping("test")
    public Object testQc() {
        List<Player> players = repository.findByPlayerItemsName("dada");
        return players;
    }
}

JSON结果

[{
    "id": 1,
    "name": "haha",
    "playerItems": [{
        "id": 1,
        "name": "dada",
        "begin": false
    }, {
        "id": 2,
        "name": "wawa",
        "begin": true
    }]
}]

我的查询条件是子对象名称等于='dada',这个条件只限制了父对象,子对象列表并没有根据这个条件进行限制

如果我想对子对象进行限制应该怎么做呢?

阅读 575
评论 2019-01-10 提问
    1 个回答
    Charles
    • 1.3k

    你的repository就是返回的List<Player>,程序就返回的Player列表,你再取player下面OneToMany的playerItem,就是这个player下面关联的所有playerItems,程序运行没问题。

    你要的效果并不能这么写,你要从PlayerItem一端选出来所有name是data的List<PlayerItem>,然后set到player里。

    评论 赞赏 2019-01-10
      撰写回答

      登录后参与交流、获取后续更新提醒