4

I need just an answer to a very specific question:

For example:

Customer c =(Customer) manager.createQuery("SELECT c FROM Customer c").getResultList().get(0);

This code works because of the use of the Java Persistence Query Language.

Customer c = (Customer) manager.createNativeQuery("SELECT * FROM Customer LIMIT 1").getSingleResult();

Using similar code and a native query casting to a Customer won't work, a ClassCastException will be raised.

That leads to the question: Is it possible to create objects as results from a native query using SQL?

4

2 に答える 2

4

I think you can, take a look at the documentation for createNativeQuery (the one with 2 params; Im having trouble with the link)

just pass the class you want into the createNativeQuery call....

于 2010-12-04T16:39:54.510 に答える
1

私は明らかにそれを見たことがありません。JQLを学ぶよりもはるかに便利な方法のようです。

ただし、潜在的な落とし穴となる可能性のある別の問題があります。場合によっては、フィールド名を大文字で入力する必要があります。

確かではありませんが、ネイティブクエリを使用する場合によくある大文字と小文字の区別の問題が発生する可能性があります。JPAはデフォルトでフィールド名を大文字にします。また、フィールド名を小文字として返す可能性のあるデータベースを使用している場合、Java文字列の比較では大文字と小文字が区別されるため、フィールドが見つからない可能性があります。これにより、結果セットは「ID」の値を検索するときにnullを返します。

Oracleフォーラムからの引用-主キーがnullであることが検出されましたが、そうではありません

迅速な回答ありがとうございます。

于 2010-12-04T17:01:08.150 に答える