Posts

Showing posts from September 7, 2010

Where to put named queries in JPA?

JPA provides multiple ways to obtain entities. There is a very simple programmatic API that allows us to get an entity by ID, there's a more elaborate one called the Criteria API and then there's a query language called JPQL (Java Persistence Query Language). JPQL is an object oriented query language that is based on the simplicity of SQL, but works directly on objects and their properties. The problem with such a language that's used inside another language (Java) is where to store the query definition. Traditionally there have been 2 solutions: Store the definitions in annotations on some entity. Construct strings holding the definitions inline in your Java code. The first solution is called a Named Query in JPA, it looks like this: @NamedQueries(value={ @NamedQuery( name = "Website.getWebsiteByUserId", query="select website from Website website where website.userId = :userId") @NamedQuery(...) }) @Entity public class Web