Page 1 of 1

About Question enthuware.oce-jpad.v6.2.570 :

Posted: Sat Sep 13, 2014 1:31 pm
by sztgeza
The first correct answer (by the solution) is:
A field of type Integer and an input parameter of type double.
Exact (e.g. int) and approximate (e.g. double) numeric values can be compared.
However:

Code: Select all

Query q = em.createQuery("SELECT i from Item i where i.id < :p_id");
q.setParameter("p_id",7.0d);
List result = q.getResultList();
throws an IllegalArgumentException:
java.lang.IllegalArgumentException: Parameter value [7.0] did not match expected type [java.lang.Integer (n/a)]
Please, could you describe in more details, how can the id (Integer) and the double parameter be compared?

Re: About Question enthuware.oce-jpad.v6.2.570 :

Posted: Sat Sep 13, 2014 9:06 pm
by admin
As per section 14.4 of JPA 2.0 Specification:
comparison_expression ::=
string_expression comparison_operator {string_expression | all_or_any_expression} |
boolean_expression { =|<>} {boolean_expression | all_or_any_expression} |
enum_expression { =|<>} {enum_expression | all_or_any_expression} |
datetime_expression comparison_operator
{datetime_expression | all_or_any_expression} |
entity_expression { = | <>} {entity_expression | all_or_any_expression} |
arithmetic_expression comparison_operator
{arithmetic_expression | all_or_any_expression}
The specification does not forbade comparing int and double. So it should be valid.
If you are getting an exception the implementation is not compliant.

HTH,
Paul.

Re: About Question enthuware.oce-jpad.v6.2.570 :

Posted: Thu Sep 20, 2018 7:30 pm
by __JJ__
sztgeza wrote:
Sat Sep 13, 2014 1:31 pm
The first correct answer (by the solution) is:
A field of type Integer and an input parameter of type double.
Exact (e.g. int) and approximate (e.g. double) numeric values can be compared.
However:

Code: Select all

Query q = em.createQuery("SELECT i from Item i where i.id < :p_id");
q.setParameter("p_id",7.0d);
List result = q.getResultList();
throws an IllegalArgumentException:
java.lang.IllegalArgumentException: Parameter value [7.0] did not match expected type [java.lang.Integer (n/a)]
Please, could you describe in more details, how can the id (Integer) and the double parameter be compared?
Quite simply I think what is happening here is that the usual Java SE rules for comparison are in place. You can observe this from the answers to the question.
Note that Java will unbox and widen but it will not widen and box.
So you can compare an Integer to a double, because it will unbox the Integer to int and then widen it to double:

Code: Select all

    public static void main(String[] args) {
        foo(2,2.2);

    }

    static void foo(Integer i, double d) {
        if(i==d) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
    }
The same thing happens with Float and double: it unboxes Float to float and widens it to double.