What is a named query?

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

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

6条回答
  •  时光取名叫无心
    2020-12-25 11:57

    Let me guess: you've stumbled upon concept of named queries and you wonder where it fits in SQL.

    Well, from my knowledge, named queries haven't got anything to do with "pure" SQL, but they're a concept found in various ORM (object relational mapping) frameworks, ala Java Persistence API.

    Basically, a named query is one way to map a name to a query that might be called several times in your code at different places.

    So, instead of using

    "SELECT i FROM Item i WHERE i.product.categoryID LIKE :cID"
    

    as a string at various places in your code, you use this:

    @NamedQuery( 
      name="MyEntity.getItemsPerProductCategory", 
      query="SELECT i FROM Item i WHERE i.product.categoryID LIKE :cID"
    )
    

    and afterwards you refer to this query using MyEntity.getItemsPerProductCategory.

    Example taken from this site.

    You might wonder why this is useful?

    A JPA implementation like Hibernate can check validity for named queries at startup, so in one way, you've got safe type checking. This will help reduce errors at runtime.

提交回复
热议问题