弹簧数据 - 存储库方法名称中的 OR 条件

2022-09-02 10:47:11

在我的Spring Data项目中,我有一个以下实体:

@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;

....

}

我需要实现一个Spring Data存储库方法,该方法将查找基于,和。对我来说更复杂的情况是,因为我需要构造一个条件,其中CardPaircardPairIdboardcardCardcard1 = card or card2 = card

是否可以通过Spring Data存储库方法名称提供此条件?

例如

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

是否可以将此条件转换为方法名称?card1 = card or card2 = card


答案 1

仅使用方法名称无法实现此目的,因为您需要将最后一个条件放在括号中:。无法从方法名称中推断出这一点,因为它仅用于涵盖基本情况。id = ? AND board = ? AND (card1 = ? OR card2 = ?)

对于您的情况,有三种方法:


答案 2

您可以在此处找到所有操作:http://docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/jpa.repositories.html 2.2.2节

findByIdAndBoardAndCard1OrCard2(cardPairId, board, card, card);

我还没有测试这个顺序,但它应该是这样的


推荐