Domanda

I got a Entity with a Integer

@Entity(name=customer)
public Customer {
    ...
    @Column
    private int number;
    ...
    //getter,setter
}

Now I want to cast this Integer in a query to compare it with an other value.

I tried this Query:

"SELECT c FROM customer c WHERE CAST(c.number AS TEXT) LIKE '1%'"

But it doesn't work.

È stato utile?

Soluzione 2

Since EJB3 EJBQL has been (almost) replaced by JPQL. In EJBQL and according to http://docs.oracle.com/cd/E11035_01/kodo41/full/html/ejb3_langref.html in JPQL as well there is no functionality to CAST a property of an entity.

So like I already told there are two options left:

  1. Use a native Query.
  2. Add special cast methods to the entities.

Altri suggerimenti

This works in some of my code using Hibernate:

SELECT c FROM customer c WHERE STR(c.number) LIKE '1%'

In general, this is what the Hibernate docs (14.10 Expressions) say on casting:

str() for converting numeric or temporal values to a readable string

cast(... as ...), where the second argument is the name of a Hibernate type, and extract(... from ...) if ANSI cast() and extract() is supported by the underlying database

You need to specify the column you're selecting from table alias c, and since EJBQL doesn't support a cast function, pass a string into the query instead of text. (This effectively allows your program to do the cast before it gets to EJBQL.)

The example below is in SQL Server, but should give you the idea:

 declare @numberText as varchar(50)
 set @numberText = '1'

 SELECT c.CustomerNumber FROM customer c 
 WHERE c.CustomerNumber  LIKE @numbertext + '%'

So instead of private int number use private string numberText.

NOTE: I edited this answer after OP confirmed EJBQL does not support a CAST function.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top