JPA: Differences between JQL and SQL
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 sim开发者_开发知识库ilar 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?
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....
I obviously haven't seen that one. It seems to be a much more convenient way than learning JQL.
But there's another issue that might be a potential pitfall: In some cases you need to enter field names in upper case letters.
I can't be sure, but you could be running into a case sensitivity issue which is quite common when using native queries. JPA defaults field names to upper case, and if you are using a database that may return fieldnames as lower case, because Java string comparisons are case sensitive the field might not be found. This will cause the resultset to return null when it looks for the value for "ID".
Quoted from Oracle Forums - primary key detected to be null, but it isn't
Thanks for your quick answer.
精彩评论