同时查询null和非null

vu8f3i0k  于 2021-08-13  发布在  Java
关注(0)|答案(0)|浏览(213)

我有一个实体:

@Getter
@Setter
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@Entity
@Table(name = "offer_categs")
public class OfferCateg {

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

   private String name;

   @Nullable
   private String image;

   @ManyToOne
   @JoinColumn(name = "parent_id")
   private OfferCateg parent;

   @OneToMany(mappedBy = "parent",
           cascade = CascadeType.REMOVE,
           fetch = FetchType.LAZY,
           orphanRemoval = true)
   private Set<OfferCateg> children; 

}

我只想创建类别和子类别。我的问题是,当使用下面的方法时,如果是根类别,则parent\u id可能为null。我该如何进行查询以允许这样做?我不能使用is null。我应该做两个查询并小心调用parent\u id值吗?

@Query(value = "SELECT * FROM offer_categs oc WHERE oc.parent_id = ?1 AND oc.name = ?2", nativeQuery = true)
OfferCateg findByNameAndParent(@Nullable Long parentId, String name);

编辑
我把查询改成了这个,它似乎在工作

@Query(value = "SELECT * FROM offer_categs oc WHERE " +
        "(oc.parent_id = ?1 AND oc.name = ?2) OR" +
        "(oc.parent_id IS NULL AND ?1 IS NULL AND oc.name = ?2)",
        nativeQuery = true)
OfferCateg findByNameAndParent(@Nullable Long parentId, String name);

但是…这不是太过分了吗?!我相信这可以做得更容易。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题