I have played with Play!framework recently and found it’s great, especially model using JPA. It helps to speed up the development process. However, as advised, we should only select necessary fields in a query, not select *. How can I use JPA to sele开发者_运维技巧ct some fields instead of all? Is it compulsory to use JPQL?
If you want to use projections, you may use the Play! JPA query facility directly:
JPA.em().createQuery("select title,author from Article");
Article.find("select title from Article");
But don't try to optimize too fast, use normal entity finders as often as you can reverting to customized projections only for performance sensitive queries. You're better caching stuff around than retrieving partial objects as you kind of break your object encapsulation and will surely get into troubles later on.
I believe you have a misconception. JPA returns entities, that is, objects persisted in the database via ORM. Which means you cannot select only some fields, you obtain all the data in the entity.
So using there is no such thing as "return only a few fields". That would apply if you were using raw SQL (jdbc).
On using JPQL, Play offers some helper methods to facilitate queries (see documentation) but otherwise yes, you must use JPQL.
although it is better now to use entities that extending the play.models. However, you can select a value resulting from a query by typing the result as :
public static void myfunction(Long id)
{
String sqlQuery = "SELECT id FROM mytable WHERE propertie="+id;
Long resultId = Mytable.find(sqlQuery).first();
}
精彩评论