16. Native SQL

With NativeQuery you can execute native SELECT SQL statements and map the results to Doctrine entities or any other result format supported by Doctrine.

NativeQuery を使用すると、ネイティブの SELECT SQL ステートメントを実行し、結果を Doctrine エンティティまたは Doctrine がサポートするその他の結果フォーマットにマップできます。

In order to make this mapping possible, you need to describe to Doctrine what columns in the result map to which entity property. This description is represented by a ResultSetMapping object.

このマッピングを可能にするには、結果のどの列がどのエンティティ プロパティにマップされるかを Doctrine に記述する必要があります。この記述は ResultSetMapping オブジェクトによって表されます。

With this feature you can map arbitrary SQL code to objects, such as highly vendor-optimized SQL or stored-procedures.

この機能を使用すると、高度にベンダー最適化された SQL やストアド プロシージャなどのオブジェクトに任意の SQL コードをマップできます。

Writing ResultSetMapping from scratch is complex, but there is a convenience wrapper around it called a ResultSetMappingBuilder. It can generate the mappings for you based on Entities and even generates the SELECT clause based on this information for you.

ResultSetMapping をゼロから記述するのは複雑ですが、ResultSetMappingBuilder と呼ばれる便利なラッパーがあります。エンティティに基づいてマッピングを生成し、この情報に基づいて SELECT 句を生成することもできます。

Note

ノート

If you want to execute DELETE, UPDATE or INSERT statements the Native SQL API cannot be used and will probably throw errors. Use EntityManager#getConnection() to access the native database connection and call the executeUpdate() method for these queries.

DELETE、UPDATE、または INSERT ステートメントを実行する場合、ネイティブ SQL API は使用できず、おそらくエラーがスローされます。EntityManager#getConnection() を使用してネイティブ データベース接続にアクセスし、これらのクエリに対して executeUpdate() メソッドを呼び出します。

16.1. The NativeQuery class

To create a NativeQuery you use the method EntityManager#createNativeQuery($sql, $resultSetMapping). As you can see in the signature of this method, it expects 2 ingredients: The SQL you want to execute and the ResultSetMapping that describes how the results will be mapped.

NativeQuery を作成するには、メソッドEntityManager#createNativeQuery($sql, $resultSetMapping) を使用します。このメソッドのシグネチャでわかるように、実行する SQL と、結果がどのようにマッピングされるかを記述する ResultSetMapping という 2 つの要素が必要です。

Once you obtained an instance of a NativeQuery, you can bind parameters to it with the same API that Query has and execute it.

NativeQuery のインスタンスを取得したら、Query と同じ API を使用してパラメーターをバインドし、それを実行できます。

<?php
use Doctrine\ORM\Query\ResultSetMapping;

$rsm = new ResultSetMapping();
// build rsm here

$query = $entityManager->createNativeQuery('SELECT id, name, discr FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

16.2. ResultSetMappingBuilder

An easy start into ResultSet mapping is the ResultSetMappingBuilder object. This has several benefits:

ResultSet マッピングを簡単に開始するには、ResultSetMappingBuilder オブジェクトを使用します。これにはいくつかの利点があります。

  • The builder takes care of automatically updating your ResultSetMapping when the fields or associations change on the metadata of an entity.

    ビルダーは、エンティティのメタデータでフィールドまたは関連付けが変更されると、ResultSetMapping を自動的に更新します。

  • You can generate the required SELECT expression for a builder by converting it to a string.

    ビルダーに必要な SELECT 式を文字列に変換して生成できます。

  • The API is much simpler than the usual ResultSetMapping API.

    この API は、通常の ResultSetMapping API よりもはるかに単純です。

One downside is that the builder API does not yet support entities with inheritance hierarchies.

欠点の 1 つは、ビルダー API がまだ継承階層を持つエンティティをサポートしていないことです。

<?php

use Doctrine\ORM\Query\ResultSetMappingBuilder;

$sql = "SELECT u.id, u.name, a.id AS address_id, a.street, a.city " .
       "FROM users u INNER JOIN address a ON u.address_id = a.id";

$rsm = new ResultSetMappingBuilder($entityManager);
$rsm->addRootEntityFromClassMetadata('MyProject\User', 'u');
$rsm->addJoinedEntityFromClassMetadata('MyProject\Address', 'a', 'u', 'address', array('id' => 'address_id'));

The builder extends the ResultSetMapping class and as such has all the functionality of it as well.

ビルダーは ResultSetMapping クラスを拡張するため、そのすべての機能も備えています。

The SELECT clause can be generated from a ResultSetMappingBuilder. You can either cast the builder object to (string) and the DQL aliases are used as SQL table aliases or use the generateSelectClause($tableAliases) method and pass a mapping from DQL alias (key) to SQL alias (value)

SELECT 句は、ResultSetMappingBuilder から生成できます。 builderobject を (文字列) にキャストして DQL エイリアスを SQL テーブル エイリアスとして使用するか、generateSelectClause($tableAliases) メソッドを使用して DQL エイリアス (キー) から SQL エイリアス (値) へのマッピングを渡すことができます。

<?php

$selectClause = $rsm->generateSelectClause(array(
    'u' => 't1',
    'g' => 't2'
));
$sql = "SELECT " . $selectClause . " FROM users t1 JOIN groups t2 ON t1.group_id = t2.id";

16.3. The ResultSetMapping

Understanding the ResultSetMapping is the key to using a NativeQuery. A Doctrine result can contain the following components:

ResultSetMapping を理解することが、aNativeQuery を使用するための鍵です。 Doctrine の結果には、次のコンポーネントを含めることができます。

  • Entity results. These represent root result elements.

    エンティティの結果。これらはルート結果要素を表します。

  • Joined entity results. These represent joined entities in associations of root entity results.

    結合エンティティの結果。これらは、ルート エンティティ結果の関連付けで結合されたエンティティを表します。

  • Field results. These represent a column in the result set that maps to a field of an entity. A field result always belongs to an entity result or joined entity result.

    フィールド結果。これらは、エンティティのフィールドにマップされる結果セット内の列を表します。フィールドの結果は、常にエンティティの結果または結合されたエンティティの結果に属します。

  • Scalar results. These represent scalar values in the result set that will appear in each result row. Adding scalar results to a ResultSetMapping can also cause the overall result to become mixed (see DQL - Doctrine Query Language) if the same ResultSetMapping also contains entity results.

    スカラー結果。これらは、各結果行に表示される結果セットのスカラー値を表します。 sameResultSetMapping にエンティティ結果も含まれている場合、スカラー結果を aResultSetMapping に追加すると、全体的な結果が混在する可能性があります (DQL - Doctrine Query Language を参照)。

  • Meta results. These represent columns that contain meta-information, such as foreign keys and discriminator columns. When querying for objects (getResult()), all meta columns of root entities or joined entities must be present in the SQL query and mapped accordingly using ResultSetMapping#addMetaResult.

    メタ結果。これらは、外部キーやディスクリミネーター列などのメタ情報を含む列を表します。オブジェクトをクエリする場合 (getResult())、ルート エンティティまたは結合されたエンティティのすべてのメタ列が SQL クエリに存在し、それに応じて ResultSetMapping#addMetaResult を使用してマップされる必要があります。

Note

ノート

It might not surprise you that Doctrine uses ResultSetMapping internally when you create DQL queries. As the query gets parsed and transformed to SQL, Doctrine fills a ResultSetMapping that describes how the results should be processed by the hydration routines.

DQL クエリを作成するときに、Doctrine が内部で ResultSetMapping を使用していることに驚かないかもしれません。クエリが解析されて SQL に変換されると、Doctrine はハイドレーション ルーチンによって結果がどのように処理されるべきかを記述する ResultSetMapping を埋めます。

We will now look at each of the result types that can appear in a ResultSetMapping in detail.

ここで、aResultSetMapping に表示される各結果タイプを詳しく見ていきます。

16.3.1. Entity results

An entity result describes an entity type that appears as a root element in the transformed result. You add an entity result through ResultSetMapping#addEntityResult(). Let’s take a look at the method signature in detail:

エンティティの結果は、変換された結果のルート要素として表示されるエンティティ タイプを記述します。 ResultSetMapping#addEntityResult() を介してエンティティ結果を追加します。メソッドのシグネチャを詳しく見てみましょう。

<?php
/**
 * Adds an entity result to this ResultSetMapping.
 *
 * @param string $class The class name of the entity.
 * @param string $alias The alias for the class. The alias must be unique among all entity
 *                      results or joined entity results within this ResultSetMapping.
 */
public function addEntityResult($class, $alias)

The first parameter is the fully qualified name of the entity class. The second parameter is some arbitrary alias for this entity result that must be unique within a ResultSetMapping. You use this alias to attach field results to the entity result. It is very similar to an identification variable that you use in DQL to alias classes or relationships.

最初のパラメーターは、エンティティークラスの完全修飾名です。 2 番目のパラメータは、ResultSetMapping 内で一意である必要がある、このエンティティ結果の任意のエイリアスです。このエイリアスを使用して、フィールドの結果をエンティティの結果に添付します。これは、DQL でクラスまたは関係のエイリアスとして使用する識別変数に非常に似ています。

An entity result alone is not enough to form a valid ResultSetMapping. An entity result or joined entity result always needs a set of field results, which we will look at soon.

エンティティの結果だけでは、validResultSetMapping を形成するのに十分ではありません。エンティティの結果または結合されたエンティティの結果には、常に一連のフィールド結果が必要です。これについては、すぐに説明します。

16.3.2. Joined entity results

A joined entity result describes an entity type that appears as a joined relationship element in the transformed result, attached to a (root) entity result. You add a joined entity result through ResultSetMapping#addJoinedEntityResult(). Let’s take a look at the method signature in detail:

結合されたエンティティの結果は、(ルート) エンティティの結果に添付された、変換された結果の結合された関係要素として現れるエンティティ タイプを記述します。 ResultSetMapping#addJoinedEntityResult() を使用して、結合されたエンティティの結果を追加します。メソッドのシグネチャを詳しく見てみましょう。

<?php
/**
 * Adds a joined entity result.
 *
 * @param string $class The class name of the joined entity.
 * @param string $alias The unique alias to use for the joined entity.
 * @param string $parentAlias The alias of the entity result that is the parent of this joined result.
 * @param object $relation The association field that connects the parent entity result with the joined entity result.
 */
public function addJoinedEntityResult($class, $alias, $parentAlias, $relation)

The first parameter is the class name of the joined entity. The second parameter is an arbitrary alias for the joined entity that must be unique within the ResultSetMapping. You use this alias to attach field results to the entity result. The third parameter is the alias of the entity result that is the parent type of the joined relationship. The fourth and last parameter is the name of the field on the parent entity result that should contain the joined entity result.

最初のパラメーターは、結合されたエンティティーのクラス名です。 2 番目のパラメータは、ResultSetMapping 内で一意である必要がある、結合されたエンティティの任意のエイリアスです。このエイリアスを使用して、フィールドの結果をエンティティの結果に添付します。 3 番目のパラメーターは、結合された関係の親の型であるエンティティ結果のエイリアスです。最後の 4 番目のパラメーターは、結合されたエンティティーの結果を含む親エンティティーの結果のフィールドの名前です。

16.3.3. Field results

A field result describes the mapping of a single column in a SQL result set to a field in an entity. As such, field results are inherently bound to entity results. You add a field result through ResultSetMapping#addFieldResult(). Again, let’s examine the method signature in detail:

フィールド結果は、エンティティ内のフィールドへの SQLresult セット内の単一の列のマッピングを記述します。そのため、フィールドの結果は本質的にエンティティの結果にバインドされます。 ResultSetMapping#addFieldResult() を介してフィールドの結果を追加します。もう一度、メソッド シグネチャを詳しく調べてみましょう。

<?php
/**
 * Adds a field result that is part of an entity result or joined entity result.
 *
 * @param string $alias The alias of the entity result or joined entity result.
 * @param string $columnName The name of the column in the SQL result set.
 * @param string $fieldName The name of the field on the (joined) entity.
 */
public function addFieldResult($alias, $columnName, $fieldName)

The first parameter is the alias of the entity result to which the field result will belong. The second parameter is the name of the column in the SQL result set. Note that this name is case sensitive, i.e. if you use a native query against Oracle it must be all uppercase. The third parameter is the name of the field on the entity result identified by $alias into which the value of the column should be set.

最初のパラメータは、フィールド結果が属するエンティティ結果のエイリアスです。 2 番目のパラメーターは、SQL 結果セット内の列の名前です。この名前は大文字と小文字が区別されることに注意してください。つまり、Oracle に対してネイティブ クエリを使用する場合は、すべて大文字にする必要があります。 3 番目のパラメーターは、列の値を設定する $alias によって識別されるエンティティ結果のフィールドの名前です。

16.3.4. Scalar results

A scalar result describes the mapping of a single column in a SQL result set to a scalar value in the Doctrine result. Scalar results are typically used for aggregate values but any column in the SQL result set can be mapped as a scalar value. To add a scalar result use ResultSetMapping#addScalarResult(). The method signature in detail:

スカラー結果は、Doctrine 結果のスカラー値への SQLresult セット内の単一の列のマッピングを記述します。通常、スカラー結果は集計値に使用されますが、SQLresult セット内の任意の列をスカラー値としてマップできます。スカラー結果を追加するには、ResultSetMapping#addScalarResult() を使用します。メソッド署名の詳細:

<?php
/**
 * Adds a scalar result mapping.
 *
 * @param string $columnName The name of the column in the SQL result set.
 * @param string $alias The result alias with which the scalar result should be placed in the result structure.
 */
public function addScalarResult($columnName, $alias)

The first parameter is the name of the column in the SQL result set and the second parameter is the result alias under which the value of the column will be placed in the transformed Doctrine result.

最初のパラメーターは SQL 結果セット内の列の名前で、2 番目のパラメーターは、変換された Doctrine の結果で列の値が配置される結果エイリアスです。

16.3.5. Meta results

A meta result describes a single column in a SQL result set that is either a foreign key or a discriminator column. These columns are essential for Doctrine to properly construct objects out of SQL result sets. To add a column as a meta result use ResultSetMapping#addMetaResult(). The method signature in detail:

メタ結果は、外部キーまたは識別子列のいずれかである SQL 結果セット内の単一の列を表します。これらの列は、Doctrine が SQLresult セットからオブジェクトを適切に構築するために不可欠です。列をメタ結果として追加するには、ResultSetMapping#addMetaResult() を使用します。メソッド署名の詳細:

<?php
/**
 * Adds a meta column (foreign key or discriminator column) to the result set.
 *
 * @param string  $alias
 * @param string  $columnAlias
 * @param string  $columnName
 * @param boolean $isIdentifierColumn
 */
public function addMetaResult($alias, $columnAlias, $columnName, $isIdentifierColumn = false)

The first parameter is the alias of the entity result to which the meta column belongs. A meta result column (foreign key or discriminator column) always belongs to an entity result. The second parameter is the column alias/name of the column in the SQL result set and the third parameter is the column name used in the mapping. The fourth parameter should be set to true in case the primary key of the entity is the foreign key you’re adding.

最初のパラメーターは、テーマ列が属するエンティティ結果のエイリアスです。メタ結果列 (外部キーまたは識別子列) は、常にエンティティ結果に属します。 2 番目のパラメーターは SQLresult セット内の列の別名/名前で、3 番目のパラメーターはマッピングで使用される列名です。エンティティの主キーが追加する外部キーである場合は、4 番目のパラメーターを true に設定する必要があります。 .

16.3.6. Discriminator Column

When joining an inheritance tree you have to give Doctrine a hint which meta-column is the discriminator column of this tree.

継承ツリーに参加するとき、Doctrine にどのメタ列がこのツリーの識別子列であるかのヒントを与える必要があります。

<?php
/**
 * Sets a discriminator column for an entity result or joined entity result.
 * The discriminator column will be used to determine the concrete class name to
 * instantiate.
 *
 * @param string $alias The alias of the entity result or joined entity result the discriminator
 *                      column should be used for.
 * @param string $discrColumn The name of the discriminator column in the SQL result set.
 */
public function setDiscriminatorColumn($alias, $discrColumn)

16.3.7. Examples

Understanding a ResultSetMapping is probably easiest through looking at some examples.

ResultSetMapping を理解するには、いくつかの例を見るのがおそらく最も簡単です。

First a basic example that describes the mapping of a single entity.

最初に、単一エンティティのマッピングを説明する基本的な例を示します。

<?php
// Equivalent DQL query: "select u from User u where u.name=?1"
// User owns no associations.
$rsm = new ResultSetMapping;
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');

$query = $this->_em->createNativeQuery('SELECT id, name FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

The result would look like this:

結果は次のようになります。

array(
    [0] => User (Object)
)

Note that this would be a partial object if the entity has more fields than just id and name. In the example above the column and field names are identical but that is not necessary, of course. Also note that the query string passed to createNativeQuery is real native SQL. Doctrine does not touch this SQL in any way.

エンティティに id と name 以外のフィールドがある場合、これは部分オブジェクトになることに注意してください。上記の例では、列名とフィールド名は同じですが、もちろんその必要はありません。また、createNativeQuery に渡されるクエリ文字列は実際のネイティブ SQL であることに注意してください。 Doctrine はこの SQL に一切触れていません。

In the previous basic example, a User had no relations and the table the class is mapped to owns no foreign keys. The next example assumes User has a unidirectional or bidirectional one-to-one association to a CmsAddress, where the User is the owning side and thus owns the foreign key.

前の基本的な例では、ユーザーにはリレーションがなく、クラスがマップされるテーブルは外部キーを所有していません。次の例では、User が CmsAddress に対して単方向または双方向の 1 対 1 の関連付けを持っていると想定しています。ここで、User は所有側であり、したがって外部キーを所有しています。

<?php
// Equivalent DQL query: "select u from User u where u.name=?1"
// User owns an association to an Address but the Address is not loaded in the query.
$rsm = new ResultSetMapping;
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addMetaResult('u', 'address_id', 'address_id');

$query = $this->_em->createNativeQuery('SELECT id, name, address_id FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

Foreign keys are used by Doctrine for lazy-loading purposes when querying for objects. In the previous example, each user object in the result will have a proxy (a “ghost”) in place of the address that contains the address_id. When the ghost proxy is accessed, it loads itself based on this key.

外部キーは、オブジェクトをクエリする際の遅延読み込みの目的で Doctrine によって使用されます。前の例では、結果の各ユーザー オブジェクトには、address_id を含むアドレスの代わりにプロキシ (「ゴースト」) があります。ゴースト プロキシがアクセスされると、このキーに基づいて自身をロードします。

Consequently, associations that are fetch-joined do not require the foreign keys to be present in the SQL result set, only associations that are lazy.

したがって、フェッチ結合されたアソシエーションでは、外部キーが SQL 結果セットに存在する必要はなく、レイジーなアソシエーションのみが必要です。

<?php
// Equivalent DQL query: "select u from User u join u.address a WHERE u.name = ?1"
// User owns association to an Address and the Address is loaded in the query.
$rsm = new ResultSetMapping;
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addJoinedEntityResult('Address' , 'a', 'u', 'address');
$rsm->addFieldResult('a', 'address_id', 'id');
$rsm->addFieldResult('a', 'street', 'street');
$rsm->addFieldResult('a', 'city', 'city');

$sql = 'SELECT u.id, u.name, a.id AS address_id, a.street, a.city FROM users u ' .
       'INNER JOIN address a ON u.address_id = a.id WHERE u.name = ?';
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

In this case the nested entity Address is registered with the ResultSetMapping#addJoinedEntityResult method, which notifies Doctrine that this entity is not hydrated at the root level, but as a joined entity somewhere inside the object graph. In this case we specify the alias ‘u’ as third parameter and address as fourth parameter, which means the Address is hydrated into the User::$address property.

この場合、ネストされたエンティティ Address は ResultSetMapping#addJoinedEntityResult メソッドで登録され、Doctrine にこのエンティティがルート レベルでハイドレートされていないことを通知しますが、オブジェクト グラフ内のどこかで結合されたエンティティとして通知されます。この場合、エイリアス「u」を 3 番目のパラメータとして指定し、アドレスを 4 番目のパラメータとして指定します。これは、アドレスが User::$address プロパティにハイドレートされることを意味します。

If a fetched entity is part of a mapped hierarchy that requires a discriminator column, this column must be present in the result set as a meta column so that Doctrine can create the appropriate concrete type. This is shown in the following example where we assume that there are one or more subclasses that extend User and either Class Table Inheritance or Single Table Inheritance is used to map the hierarchy (both use a discriminator column).

フェッチされたエンティティが識別子列を必要とするマップされた階層の一部である場合、Doctrine が適切な具象型を作成できるように、この列はメタ列として結果セットに存在する必要があります。これを次の例に示します。ここでは、User を拡張する 1 つ以上のサブクラスがあり、Class Table Inheritance または Single Table Inheritance のいずれかを使用して階層をマップするとします (どちらも識別子列を使用します)。

<?php
// Equivalent DQL query: "select u from User u where u.name=?1"
// User is a mapped base class for other classes. User owns no associations.
$rsm = new ResultSetMapping;
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addMetaResult('u', 'discr', 'discr'); // discriminator column
$rsm->setDiscriminatorColumn('u', 'discr');

$query = $this->_em->createNativeQuery('SELECT id, name, discr FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

Note that in the case of Class Table Inheritance, an example as above would result in partial objects if any objects in the result are actually a subtype of User. When using DQL, Doctrine automatically includes the necessary joins for this mapping strategy but with native SQL it is your responsibility.

クラス テーブルの継承の場合、上記の例では、結果のオブジェクトが実際にユーザーのサブタイプである場合、部分的なオブジェクトになることに注意してください。 DQL を使用する場合、Doctrine はこのマッピング戦略に必要な結合を自動的に含めますが、ネイティブ SQL の場合はユーザーの責任です。

16.4. Named Native Query

Note

ノート

Named Native Queries are deprecated as of version 2.9 and will be removed in ORM 3.0

名前付きネイティブ クエリはバージョン 2.9 で非推奨になり、ORM 3.0 で削除されます

You can also map a native query using a named native query mapping.

名前付きネイティブ クエリ マッピングを使用して、ネイティブ クエリをマップすることもできます。

To achieve that, you must describe the SQL resultset structure using named native query (and sql resultset mappings if is a several resultset mappings).

これを実現するには、名前付きネイティブ クエリを使用して SQL 結果セット構造を記述する必要があります (複数の結果セット マッピングがある場合は、SQL 結果セット マッピング)。

Like named query, a named native query can be defined at class level or in a XML or YAML file.

名前付きクエリと同様に、名前付きネイティブ クエリは、クラス レベルまたは XML または YAML ファイルで定義できます。

A resultSetMapping parameter is defined in @NamedNativeQuery, it represents the name of a defined @SqlResultSetMapping.

resultSetMapping パラメータは @NamedNativeQuery で定義され、定義された @SqlResultSetMapping の名前を表します。

Things to note:
  • The resultset mapping declares the entities retrieved by this native query.

    結果セット マッピングは、このネイティブ クエリによって取得されるエンティティを宣言します。

  • Each field of the entity is bound to a SQL alias (or column name).

    エンティティの各フィールドは、SQL エイリアス (または列名) にバインドされます。

  • All fields of the entity including the ones of subclasses and the foreign key columns of related entities have to be present in the SQL query.

    サブクラスのものを含むエンティティのすべてのフィールドと、関連するエンティティの外部キー列が SQL クエリに存在する必要があります。

  • Field definitions are optional provided that they map to the same column name as the one declared on the class property.

    フィールド定義は、クラス プロパティで宣言されたものと同じ列名にマップされる場合、オプションです。

  • __CLASS__ is an alias for the mapped class

    __CLASS__ はマップされたクラスのエイリアスです

In the above example, the fetchJoinedAddress named query use the joinMapping result set mapping. This mapping returns 2 entities, User and Address, each property is declared and associated to a column name, actually the column name retrieved by the query.

上記の例では、fetchJoinedAddress という名前のクエリは、joinMapping 結果セット マッピングを使用します。このマッピングは、User と Address の 2 つのエンティティを返します。各プロパティは宣言され、列名 (実際にはクエリによって取得された列名) に関連付けられます。

Let’s now see an implicit declaration of the property / column.

プロパティ/列の暗黙の宣言を見てみましょう。

In this example, we only describe the entity member of the result set mapping. The property / column mappings is done using the entity mapping values. In this case the model property is bound to the model_txt column. If the association to a related entity involve a composite primary key, a @FieldResult element should be used for each foreign key column. The @FieldResult name is composed of the property name for the relationship, followed by a dot (“.”), followed by the name or the field or property of the primary key.

この例では、結果セット マッピングのエンティティ メンバーのみを記述します。プロパティ/列のマッピングは、エンティティ マッピング値を使用して行われます。この場合、モデル プロパティは model_txt 列にバインドされます。関連するエンティティへの関連付けが含まれる場合複合主キー、@FieldResult 要素は、各外部キー列に使用する必要があります。@FieldResult 名は、リレーションシップのプロパティ名と、それに続くドット (「.」) で構成され、その後に名前またはフィールドまたは主キーのプロパティ。

If you retrieve a single entity and if you use the default mapping, you can use the resultClass attribute instead of resultSetMapping:

単一のエンティティを取得し、デフォルトのマッピングを使用する場合は、resultSetMapping の代わりに resultClass 属性を使用できます。

In some of your native queries, you’ll have to return scalar values, for example when building report queries. You can map them in the @SqlResultsetMapping through @ColumnResult. You actually can even mix, entities and scalar returns in the same native query (this is probably not that common though).

一部のネイティブ クエリでは、レポート クエリを作成する場合など、スカラー値を返す必要があります。@ColumnResult を介して @SqlResultsetMapping でそれらをマッピングできます。実際には、同じネイティブ クエリでエンティティとスカラーの戻り値を混在させることもできます。 (これはおそらくそれほど一般的ではありません)。

Table Of Contents

Previous topic

15. The QueryBuilder

15. QueryBuilder

Next topic

17. Change Tracking Policies

17. 変更追跡ポリシー

This Page

Fork me on GitHub