Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 named queries

I can't find any documentation about named queries in Doctrine2. Please help. Does Doctrine2 have a named queries feature?

like image 985
Mikhail Avatar asked Aug 18 '12 06:08

Mikhail


People also ask

What are named queries?

A named query is a SQL expression represented as a table. In a named query, you can specify an SQL expression to select rows and columns returned from one or more tables in one or more data sources.

How JPA named queries work?

A named query is a predefined query that you create and associate with a container-managed entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager . At run time, you can use the EntityManager to acquire, configure, and execute a named query.

What is named query annotation?

Annotation Type NamedQuery. Specifies a static, named query in the Java Persistence query language. Query names are scoped to the persistence unit. The NamedQuery annotation can be applied to an entity or mapped superclass.


2 Answers

Maybe you'll be interested by the EntityRepositories where you can create and store complex Doctrine queries, and call theme in your project where you want:

http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

like image 35
guillaumepotier Avatar answered Oct 14 '22 15:10

guillaumepotier


You can use

  1. NamedQuery - DQL. Example

    use Doctrine\ORM\Mapping\NamedQuery;
    use Doctrine\ORM\Mapping\NamedQueries;
    
    /**
    * @Entity
    * @Table(name="cms_users")
    * @NamedQueries({
    *     @NamedQuery(name="activated", query="SELECT u FROM __CLASS__ u WHERE u.status = 1")
    * })
    */
    class CmsUser
    {}
    

    And call it like

    $this->getDoctrine()->getRepository('MyBundle:CmsUser')
        ->createNamedQuery('activated')
        ->getResult();
    
  2. NamedNativeQuery - SQL. More information here: http://docs.doctrine-project.org/en/latest/reference/native-sql.html#named-native-query

  3. Collecting a queries in your EntityRepository, like:

    namespace Acme\StoreBundle\Repository;
    
    use Doctrine\ORM\EntityRepository;
    
    class ProductRepository extends EntityRepository
    {
        public function findAllOrderedByName()
        {
            return $this->getEntityManager()
                ->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')
                ->getResult();
        }
    }
    

    More information here: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

Similar topic here: https://groups.google.com/forum/?fromgroups#!topic/doctrine-user/K-D5ta5tZ3Y[1-25]

like image 50
Mikhail Avatar answered Oct 14 '22 15:10

Mikhail