'JPA equivalent of PostgreSQL with null comparison

I have a requirement something like there are two db tables A and B. Table A and table B both have column 'merit' of type integer. The requirement is to find the entries from table A those have merit that matches with the least merit number in table B.
If merit in B is NULL for all the entries, the query should result all the entries from table A.
If merit in B has valid numbers, the query should result the entries of A those match the least merit number in table B.

Sample data is like this::

      TABLE A                TABLE B
   COL1 COL2 MERIT        COL1  COL2 MERIT
    a    ab   1            c    ac    1
    b    bc   2            d    ad    3

From above data the least merit in B is 1 so, only the matching entry should result from Table A.
If merit column in B is null for all the entries ie. B has no valid number for merit, two entries from A should result.

So, I came up with the below sql query::

   select A.* from A where A.merit IS NOT DISTINCT FROM (
   select min(B.merit) from B where B.merit IS NOT NULL);

I am unable to write the JPA equivalent of this sql because of "IS NOT DISTINCT FROM".
The below queries are not working.

select a from A a where a.merit in (select min(b.merit) from B b where b.merit is not null)
select a from A a where a.merit = (select min(b.merit) from B b where b.merit is not null)

My environment is POSTGRESQL, HIBERNATE in QUARKUS.

Thanks for any suggestions.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source