Spring Data - OR condition in a repository method

2019-04-19 01:20发布

In my Spring Data project I have a following entity:

@Entity
@NamedEntityGraph(name = "graph.CardPair", attributeNodes = {})
@Table(name = "card_pairs")
public class CardPair extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 7571004010972840728L;

    @Id
    @SequenceGenerator(name = "card_pairs_id_seq", sequenceName = "card_pairs_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "card_pairs_id_seq")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "card1_id")
    private Card card1;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "card2_id")
    private Card card2;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "selected_card_id")
    private Card selectedCard;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "board_id")
    private Board board;

....

}

I need to implement a Spring Data repository method that will look for a CardPair based on cardPairId, board and card. The more complicated case to me is a Card because I need to construct a condition where card1 = card or card2 = card

Is it possible to provide this condition via Spring Data repository method name ?

For example

cardPairRepository.findByIdAndBoardAnd[card1 = card or card2 = card]AndSelectedCardIsNull(cardPairId, board, card);

Is it possible to translate this condition card1 = card or card2 = card in a method name ?

2条回答
地球回转人心会变
2楼-- · 2019-04-19 02:13

You can find all operations here: http://docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/jpa.repositories.html section 2.2.2

findByIdAndBoardAndCard1OrCard2(cardPairId, board, card, card);

I haven't testen the order of this, but it should be something like this

查看更多
Melony?
3楼-- · 2019-04-19 02:15

It is impossible to achieve this using just method name since you need the last condition to be in parentheses: id = ? AND board = ? AND (card1 = ? OR card2 = ?). There is no way to infer this from method name since it is intended to cover basic cases only.

There are three ways in your case:

查看更多
登录 后发表回答