Anda di halaman 1dari 18

Sun

Forums
Welcome
• Lo
gin
• Wa
Query.get tch
SingleRes Lis
Top of Form
ult returns t
Reply »
a Vector? 10903682
• Be
gin
2010 Jan Bottom of Form
ner
11 03:53 s
Qui
ck
Hallo Sta
rt
I tested on glassfish 2.1 with
oracle.toplink.essentials.PersistenceProvider. Running a • My
test with the entitymanager i noticed that getSingleResult For
returns a vector containing only one element rather than um
an object that i could cast accordingly. s
• Fee
Looking in the web and also taking a look at the spec all dba
example cast the result directly rather than assuming a ck
vector/list. • FA
Q
Since the specification just wants Object as result type
this is not wrong but does that really pass compatibility • Co
tests? de
of
regards Co
ndu
ct
Top of Form
Top of Form
Bottom of
10903962
jtahlborn Form
Re: Query.getSingleResult returns a Vector? Search
Posts:2.066 2010 Jan 11 08:14 (reply 1 of 8) (In reply to original Reply » Forums
post ) D is c u s s io n »F o r u m

Registered: Bottom of
26/01/08 Form f o r u m s .s u n .c o m

Search

what query are you running?

Top of Form
10903971
mark197
1 Re: Query.getSingleResult returns a Vector?
Reply »
Registered:
Bottom of
2/28/03 Form

Select count(*) from <tablename>

In return i get a java.util.Vector containing the count.


Query query = em.createNativeQuery("select
count(*) from soc");
List v = (List) query.getSingleResult();

Edited by: mark1971 on Jan 11, 2010 8:21 AM A Sun Developer


Oracle Social Media Participation Policy | Network Site
About Sun | About This Site | Newsletters
| Contact Us | Employment Unless otherwise
Top of Form
How to Buy | Licensing | Terms of Use | licensed, code in all
jtahlborn Privacy | Trademarks technical manuals
Re: Query.getSingleResult returns a Vector? herein (including
Posts:2.066 2010 Jan 11 09:15 (reply 3 of 8) (In reply to #2 ) articles, FAQs,
samples) is provided
Registered: © 2009, Oracle Corporation and/or its under
Bottom of this License.
26/01/08 affiliates Form

Content Feeds

oddly, i couldn't find anything in the jpa documentation


Cast Functions and
or spec which Operators
nailed down exactly what a native query
Table 11.13.should return in this situation. if use the 2-arg method,
Cast Functions
though, it seems like jpa is supposed to return a single
Name object.Description
i'd try "em.createNativeQuery("the query",
Integer.class)" or some similar number type.
Cast a string to a binary
BINARY
string

Cast a value as a certain Top of Form


CAST()
type
mark197
1 Re: Query.getSingleResult returns a Vector?
Cast
2010 aJan
value as a (reply
11 09:27 certain4 of 8) (In reply to #3 )
Convert()
Posts:62 type
Registered:
Bottom of
2/28/03
• BINARY Form

The BINARY operator casts the string following it to a binary string. This is an easy way to
force a column comparison to be done byte by byte rather than character by character.
This causes
You arethe comparison
right to be case
it is not nailed down.sensitive
From myeven
bookif the
andcolumn is not defined as
various examples i thought that an Object or Object[]significant.
BINARY or BLOB . BINARY also causes trailing spaces to be was
returned
mysql> and'a'
SELECT you =then cast accordingly but maybe this is
'A';
-> 1
only true for hibernate. Since i am bound to toplink in this
mysql> SELECT BINARY 'a' = 'A';
case ->
i am0 screwed.
mysql> SELECT 'a' = 'a ';
Regarding
-> 1 the additional paramaeter, this also fails, i tried
thatSELECT
mysql> before: BINARY 'a' = 'a ';
Query query = em.createNativeQuery("select
count(*) from soc",Integer.class);
results in
[TopLink Warning]: 2010.01.11 06:24:23.070--
UnitOfWork(12359283)--Exception [TOPLINK-6007]
(Oracle TopLink Essentials - 2.1 (Build b60e-
fcs (12/23/2008))):
ption
Exception Description: Missing descriptor for
[class java.lang.Integer].
Query: ReadAllQuery(java.lang.Integer)
Exception in thread "main" Local Exception
Stack:
Exception
-> 0 [TOPLINK-6007] (Oracle TopLink
Essentials - 2.1 (Build b60e-fcs
In a comparison, BINARY affects the entire operation; it can be given before either
(12/23/2008))):
oracle.toplink.essentials.exceptions.QueryExce
operand with the same result.
ption
BINARY str is shorthand
Exception for CAST(
Description: BINARY).
str AS descriptor
Missing for
[class java.lang.Integer].
Note Query:
that in some contexts, if you cast an indexed column to BINARY, MySQL is not able
ReadAllQuery(java.lang.Integer)
to use the indexatefficiently.
• oracle.toplink.essentials.exceptions.QueryExce
CAST(expr AS type)
ption.descriptorIsMissing(QueryException.java:
The CAST()
419) function takes a value of one type and produce a value of another type,
similar
. to CONVERT(). See the description of CONVERT() for more information.
• CONVERT(expr,type), CONVERT(expr USING transcoding_name)
The CONVERT() and CAST() functions take a value of one type and produce a value of
Top of Form
another type.
jtahlborn
The type can be one of the following values:
Re: Query.getSingleResult returns a Vector?
Posts:2.066○ 2010
BINARY[(N)]
Jan 11 10:57 (reply 5 of 8) (In reply to #4 )
○ CHAR[(N)]
Registered: Bottom of
26/01/08 ○ DATE Form

○ DATETIME
○ DECIMAL[(M[,D])]
○ mark1971
SIGNED wrote:
[INTEGER]
You are right it is not nailed down. From my book and
○ various
TIME examples i thought that an Object or Object[] was
○ returned
UNSIGNEDand you then cast accordingly but maybe this is
[INTEGER]
only true for hibernate.
BINARY produces a string with the BINARY data type. See Section 10.4.2, “The BINARY
and VARBINARY
i think thatTypes” for a down
is all nailed description
for jpaofquery
how this affects comparisons. If the optional
language
lengthqueries,
N is given, BINARY(N) causes
just not for native queries.the cast to use no more than N bytes of the argument.
As of MySQL 5.0.17, values shorter than N bytes are padded with 0x00 bytes to a length
of N. speaking of which are you querying a table which is
CHAR(mapped
N) causesto an
theentity?
cast to ifuse
so,noyou could
more thandoNthis query using
characters of the argument.
the jpa query language, and then i think the result
The DECIMAL type is available as of MySQL 5.0.8.
would/should be a single value.
CAST() and CONVERT(... USING ...) are standard SQL syntax. The non-USING form of
CONVERT() is ODBC syntax.
CONVERT() with USING is used to convert data between different character
Top of Form sets. In
MySQL, transcoding names are the same as the corresponding character set names. For
mark197
example,
1 Re: this statement converts the
Query.getSingleResult string a'abc'
returns in the default character set to the
Vector?
corresponding
2010 Janstring in the
12 01:02 utf8 character set:
(reply 6 of 8) (In reply to #5 )
Posts:62
SELECT CONVERT('abc' USING utf8);
Registered:
Normally, Bottom of
2/28/03 you cannot compare a BLOB value or other binary string in case-insensitive
Form
fashion
because binary strings have no character set, and thus no concept of lettercase. To perform a
case-insensitive comparison, use the CONVERT() function to convert the value to a nonbinary

No, the entity is not mapped to an entity but yes it returns


long if i do this
@NamedQuery(name="count", query="select
count(s) from Soc s")
that
<persistence-unit name="pu/refdata"
transaction-type="JTA">
<provider>oracle.toplink.essentials.Persi
string. If the stenceProvider</provider>
character set of the result has a case-insensitive collation, the LIKE operation is not
case sensitive: <jta-data-source>jdbc/myDataSource</jta-
SELECT 'A' data-source>
LIKE CONVERT(blob_col USING latin1) FROM tbl_name;
<class>Soc</class>
To use a different character set, substitute its name for latin1 in the preceding statement. To
ensure that a case-insensitive collation is used, specify a COLLATE clause following the
CONVERT() call.and
CONVERT() can be used
Query q2 =more generally for comparing strings that are represented in different
em.createNamedQuery("count");
character sets.
Object o = q2.getSingleResult();
LOWER() (andSystem.err.println(o.getClass().getName());
UPPER()) are ineffective when applied to binary strings (BINARY, VARBINARY,
BLOB). To perform lettercase conversion, convert the string to a nonbinary string:
mysql> SET @str = BINARY 'New York';
But adding an entity just for a count seems a bit too
mysql> SELECT LOWER(@str), LOWER(CONVERT(@str USING latin1));
much.
+-------------+-----------------------------------+
| LOWER(@str) | LOWER(CONVERT(@str USING latin1)) |
+-------------+-----------------------------------+
| New York | new york |
Top of Form
+-------------+-----------------------------------+
Thejtahlborn
cast functions are useful when you want to create a column with a specific type in a CREATE
Re: Query.getSingleResult
TABLE ... SELECT statement: returns a Vector?
Posts:2.066 2010 Jan 12 07:55 (reply 7 of 8) (In reply to #6 )
CREATE TABLE new_table SELECT CAST('2000-01-01' AS DATE);
Registered:
The functions also can be useful for sorting ENUM columns in lexical order.Bottom
Normally,
of sorting of
26/01/08 Form
ENUM columns occurs using the internal numeric values. Casting the values to CHAR results in a
lexical sort:
SELECT enum_col FROM tbl_name ORDER BY CAST(enum_col AS CHAR);
CAST(str ASmark1971 is the same thing
BINARY)wrote: as BINARY str. CAST(expr AS CHAR) treats the
expression asBut
a string with
adding an the default
entity character
just for a countset.
seems a bit too
much. the result if you use it as part of a more complex expression such as
CAST() also changes
CONCAT('Date: ',CAST(NOW() AS DATE)).
certainly. i was just saying that if it was already an entity,
You should not
thatuse CAST()
using to query
the jpa extractlanguage
data in different formats
would work but instead use string functions
better.
like LEFT() or EXTRACT(). See Section 11.7, “Date and Time Functions”.
To cast a string to a numeric value in numeric context, you normally do not have to do anything
other than to use the string value as though it were a number: Top of Form
mysql> SELECT 1+'1';
mark197
-> 2
Re: Query.getSingleResult returns a Vector?
If1 you use a number in 13
2010 Jan string context,
01:46 (replythe number
8 of 8) (Inautomatically
reply to #7 ) is converted to a string:
Posts:62
mysql> SELECT CONCAT('hello you ',2);
Registered:
-> 'hello you 2' Bottom of
2/28/03 Form
For information about implicit conversion of numbers to strings, see Section 11.2, “Type
Conversion in Expression Evaluation”.
MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using
numeric operators (such
certainly. as +just
i was or -saying
) and one
thatofifthe operands
it was alreadyis an entity,
unsigned integer, the result is
unsigned. You can
that override
using thisquery
the jpa by using the SIGNED
language would and better. cast operators to cast the
workUNSIGNED
operation to aYes,
signed or unsigned 64-bit integer, respectively.
you definitly got a point there. Before this i assumed
that for native queries only sql dialect errors could
happen, now i know that the actual entity manager
implementation influences the code :-/
mysql> SELECT CAST(1-2 AS UNSIGNED)
-> 18446744073709551615
mysql> SELECT CAST(CAST(1-2 AS UNSIGNED) AS SIGNED);
-> -1
Note that if either operand is a floating-point value, the result is a floating-point value and is not
affected by the preceding rule. (In this context, DECIMAL column values are regarded as floating-
point values.)
mysql> SELECT CAST(1 AS UNSIGNED) - 2.0;
-> -1.0
If you are using a string in an arithmetic operation, this is converted to a floating-point number.
If you convert a “zero” date string to a date, CONVERT() and CAST() return NULL when the
NO_ZERO_DATE SQL mode is enabled. As of MySQL 5.0.4, they also produce a warning.
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved. Legal
Notices

Previous / Next / Up / Table of Contents

User Comments
Posted by Are you mortal? Then prepare to die. on November 3 2004 [Delete]
11:31am [Edit]

Be careful that this 'feature' of MySQL dosn't bit you in the ass.

For example, imagine I have a table with two 'unsigned' integer columns (still with me?). Lets
call those columns 'one' and 'two'. Now imagine the following query...

# Query to select the 10 biggest differences between two colums


SELECT one - two AS diff
ORDER BY one - two
LIMIT 10;

If the result of 'one - two' is negative (imagine that the value of two is bigger than one), then you
end up with values of 18446744073709551615.

This isn't a bug mind you, as this fact is documented this is the expected behaviour!

So, still looking for the 10 biggest differences you might try...

# Query 2 to select the 10 biggest differences between two colums


SELECT one - two AS diff
WHERE one - two < 10000 -- Hopefuly bigger than our biggest differences
ORDER BY one - two
LIMIT 10;
You find it dosn't work, (you still get the 18446744073709551615s) because the internals of
subtracting unsigned columns are so messed up.

You need to do the following...

# Query 3 to select the 10 biggest differences between two colums


SELECT CAST(one - two AS SIGNED) AS diff
ORDER BY diff
LIMIT 10;

I hope this example helps


Posted by anne blankert on May 29 2006 10:14pm [Delete] [Edit]

To convert to numeric, the convert() and cast() functions are less forgiving then the implicit
conversion when it comes to the data to be converted. If you want to convert "1a" or "1 apple",
"2 apples", " 3 things" to 1, 1, 2 and 3 respectivly, the cast and convert function will produce an
error. Instead use select 0+'1a', 0+'1 apple', 0+'2 apples', 0+' 3 things'.
Posted by Ronald Rudy on December 5 2006 5:07pm [Delete] [Edit]

Here's a workaround for not being able to cast/convert a value during table creation with just a
create:

CREATE TEMPORARY TABLE tmp


SELECT 1000000.001-1000000.001 as n;

This will yield a table with the following structure:


+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| n | double(20,3) | | | 0.000 | |
+-------+--------------+------+-----+---------+-------+
Posted by Mohamed Infiyaz Zaffer Khalid on January 4 2008 10:07am [Delete] [Edit]

The cast() function is amazingly useful when working with dates - not to mention date+time.

First, take a look at the following basic example:

select cast('2007-12-25' as DATETIME)

This naturally returns the output:


2007-12-25 00:00:00

But there are REALLY useful practical situations where we'd HAVE to use this function. Here's
a case:

I want to pick all records from a table "Sales", where the "TransactionDate" field is between 25-
Dec-2007 and 25-Jan-2008. Bear in mind that the field is of type DateTime.
Here's the BASIC query that I'd put in a string if I were to do it in PHP:

"SELECT * FROM Sales WHERE TransactionDate BETWEEN '$D1' and $D2"

In the above case, I'm assuming that $D1 and $D2 are posted variables in PHP. Unfortunately
The above line won't work. And THIS is where we can use the CAST() function.

So here's the CORRECT STATEMENT:

"SELECT * FROM Sales WHERE TransactionDate BETWEEN CAST('$D1' as DATETIME)


and CAST($D2 as DATETIME)"

This does the job without a flaw!


Happy programming,
Khalid

Posted by Ice Fire on August 26 2008 4:02pm [Delete] [Edit]

Alphanumeric strings automatically evaluate to 0 when used in a SELECT query to match


against a column of type INT.

For example:

Table T1
n: INT
n_squared: INT,

n n_squared
00
11
24
39
4 16
...

Q1: SELECT * FROM T1 WHERE n_squared='ABC';


Q2: SELECT * FROM T1 WHERE n_squared='ABC123';

Both queries produce identical results:

n n_squared
00
Posted by The Lynxy on March 9 2009 8:56am [Delete] [Edit]

MySQL 5.1 returns a 64-bit integer when using CAST(). For those looking to cast a 32-bit
signed integer to a 32-bit unsigned integer: you can use the function this way.
Converting -1062731519 to an unsigned integer (this number is the decimal value of
192.168.1.1):

SELECT CAST(('-1062731519' & 0xFFFFFFFF) AS UNSIGNED INTEGER);

Result is 3232235903, which is correct.


Posted by D'n Russler on June 3 2009 11:09am [Delete] [Edit]

To save others time in searching for something that wasn't immediately obvious to me...

A list of character sets is in 9.1.12. Character Sets and Collations That MySQL Supports,
http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html

Posted by Jon Lewis on February 24 2010 5:42pm [Delete] [Edit]

Here's another workaround for the lack of data types: create your own conversion function. I am
working with a DB (unfortunately) converted from and used by MS Access. All the primary keys
are therefor of type INT(10) SIGNED. When UNIONing a constant integer (SELECT 0 AS Key)
with a queried value the result is of the wrong type. So, since "CAST(0 AS INT(10))" is not an
option I created my own:

CREATE FUNCTION `IntToInt10`(TheInt INT)


RETURNS INT(10) SIGNED -- here is the trick
DETERMINISTIC
BEGIN
RETURN TheInt;
END

Now, whenever I need to force a result to be of type int(10) I just run it through this function. I'm
sure it would work for other types too (although a bit more involved if converting between two
different classes of data such as numeric to alpha). Hope that helps.
Posted by guillaume - on June 23 2010 3:14pm [Delete] [Edit]

If you need to convert an id to a part of a string, the easiest way is to:

WHERE dst LIKE CONCAT("%", CAST(fs.nid as BINARY),"%")

Posted by [name withheld] on August 25 2010 10:01am [Delete] [Edit]

Are you searching for <b><a href="http://www.coachs.cc">coach outlet</a></b> from aperture


store? Accept you begin no one in your round? You don’t anguish because now it is not charge
to go to the <strong><a href="http://www.coachs.cc">coach outlet store online</a></strong> for
accepting a abatement <strong><a href="http://www.coachs.cc">coach handbags</a></strong>.
Add your own comment.

Anda mungkin juga menyukai