What is a named query?

后端 未结 6 395
感情败类
感情败类 2020-12-25 11:00

I have read its definition but not able to understand fully.

6条回答
  •  失恋的感觉
    2020-12-25 11:44

    There are 2 ways to define queries in JPA, Dynamically and Statically. Named queries are the latter (i.e. static). You would define the query in an XML metadata file or on an actual entity directly. Note that these queries have global scope (i.e. across the entire persistence unit), i.e. no matter where they are defined the names must be unique, e.g. if you define a named query on and Entity "Employee" and the named query is called "findAll" and you have another named query called "findAll" defined on an Entity called "Department", then these queries will clash.

    That is generally why named queries' names are prefix with the Entity name to which they apply, for example:

        @NamedQueries({@NamedQuery(name="Employee.findAll", query="select e from Employee e"),
                   @NamedQuery(name="Employee.findByName", query="select e from Employee e where e.name = :name")})
        @Entity
        public class Employee ... {
        ....
    

    As a general best practice, any queries that do not need to be built up dynamically (e.g. a query that has an indeterminate amount of and clauses at compile time since these are determined by user defined filters at runtime would need to be built up dynamically) should be done through a native query since they are processed / converted to SQL once on app startup as opposed to every time the query is used. So they are more efficient than dynamic queries.

提交回复
热议问题