MyBatis動的SQLを学ぶ
sql チュートリアルSQL MyBatis SQL の強力な機能の紹介
推奨 (無料): sql チュートリアル
動的 SQL
MyBatis の強力な機能の 1 つは動的 SQL です。 JDBC または他の同様のフレームワークの使用経験がある場合は、さまざまな条件に基づいて SQL ステートメントを結合する難しさを理解できるでしょう。たとえば、スプライスするときは、必要なスペースを忘れずに追加し、リストの最後の列名からカンマを削除するように注意してください。この問題を完全に取り除くには、動的 SQL 機能を利用してください。
これまで動的 SQL を使用するのは簡単ではありませんでしたが、MyBatis は、あらゆる SQL マッピング ステートメントで使用できる強力な動的 SQL 言語を提供することでこの状況を改善しました。
動的 SQL 要素は、JSTL または XML ベースのテキスト プロセッサに似ています。 MyBatis の以前のバージョンでは、理解するのに時間がかかる要素がたくさんありました。 MyBatis 3 では要素の種類が大幅に簡略化され、元の要素の半分を学習するだけで済みます。 MyBatis は強力な OGNL ベースの式を使用して、他のほとんどの要素を排除します。
準備
最初にユーザー エンティティ クラスを作成します
public class User { private Integer id; private String username; private String userEmail; private String userCity; private Integer age;}
ユーザー テーブルを作成します
CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(255) DEFAULT NULL, user_email varchar(255) DEFAULT NULL, user_city varchar(255) DEFAULT NULL, age int(11) DEFAULT NULL, PRIMARY KEY (id))
if
インターフェースメソッドの定義
public List<User> findByUser(User user);
インターフェースに対応するMapper.xmlの定義は次のとおりです
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user where <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if></select>
ifタグのテストがtrueの場合、SQL文はif タグ内は Splicing になります。
username、userEmail、および userCity が空でない場合、SQL は以下に示すように結合されます
select id, username, user_email userEmail, user_city userCity, age from user where username = ? and user_email = ? and user_city = ?
ユーザー名のみが空でない場合、SQL は結合されます以下に示すように
select id, username, user_email userEmail, user_city userCity, age from user where username = ?
ただし、この方法には欠点があり、このとき username は空であり、userEmail と userCity は空ではないとします。
動的 SQL コードを分析してみましょう。現在、ユーザー名には値が割り当てられていないため、つまり username==null であるため、「username=#{username}」コードは SQL ステートメントに追加されません。最終的に結合された動的 SQL は次のようになります:
select id, username, user_email userEmail, user_city userCity, age from user where and user_email = ? and user_city = ?
where のすぐ後に and が続きますが、これは明らかな構文エラーです。このとき、where# に続く
and は次のようになります。 ## は削除する必要があります。この問題を解決するには、
where タグを使用します。
#where
上記の SQL をタグ内の<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <where> <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if> </where> </select>
where##if に変更します。
タグが条件を満たしている場合、where
タグは where ステートメントに接続されます。if
タグで接続された SQL の先頭に and ステートメントがある場合、フロントにすると、 and が where ステートメントに結合されます。この方法を利用すると、SQL中の不要なキーワードが自動的に削除されるので、一般的にifタグとwhereタグを組み合わせて使用します。
trim
trim タグの prefix
属性と suffix
属性は、次の目的で使用されます。実際の SQL ステートメントは、ラベル内のステートメントと結合されます。
または suffixOverrides
属性で指定された値がステートメントの前後に見つかった場合、MyBatis はそれらを自動的に削除します。複数の値を指定する場合は、後続の SQL に接続されないように、各値の後にスペースを入れることを忘れないでください。
: 結合された SQL ステートメントに接頭辞を追加します。
suffix: 結合された SQL ステートメントに接尾辞を追加します
prefixOverrides: 接続された SQL ステートメントの前に prefixOverrides が見つかった場合、MyBatis はそれらを自動的に削除します。
: Ifこれは、結合された SQL ステートメント suffixOverrides の後に発生します。MyBatis はそれらを自動的に削除します。以下の
タグを使用して、where の関数を実装します。
tag<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><select id="findByUser" resultType="com.example.mybatis.entity.User">
select
id, username, user_email userEmail, user_city userCity, age
from user <trim prefix="where" prefixOverrides="and">
<if test="username != null and username != &#39;&#39;">
username = #{username} </if>
<if test="userEmail != null and userEmail != &#39;&#39;">
and user_email = #{userEmail} </if>
<if test="userCity != null and userCity != &#39;&#39;">
and user_city = #{userCity} </if>
</trim>
</select></pre><div class="contentsignin">ログイン後にコピー</div></div>
ユーザー名が空で、userEmail と userCity が空でない場合、
ラベル結合の SQL ステートメントは次のとおりです。<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">and user_email = #{userEmail} and user_city = #{userCity}</pre><div class="contentsignin">ログイン後にコピー</div></div>
理由は、
ラベルは prefixOverrides="and" で設定されており、上記の SQL ステートメントの前に and ステートメントがあるため、上記の and ステートメントを削除する必要があります。タグが prefix="where" で設定されている場合は、結合された SQL ステートメントの前に where ステートメントを追加する必要があります。 Finally
trim
タグの SQL ステートメントが結合されます次のように
where user_email = #{userEmail} and user_city = #{userCity}
choose
すべての条件文に適用したくないが、そのうちの 1 つだけを選択したい場合があります。この状況に備えて、MyBatis は Java の switch ステートメントに似たchoose 要素を提供します。 <select id="findByUser" resultType="com.example.mybatis.entity.User">
select
id, username, user_email userEmail, user_city userCity, age
from user <where>
<choose>
<when test="username != null and username != ''">
username = #{username} </when>
<when test="userEmail != null and userEmail != ''">
and user_email = #{userEmail} </when>
<when test="userCity != null and userCity != ''">
and user_city = #{userCity} </when>
</choose>
</where>
</select>
ログイン後にコピー
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <where> <choose> <when test="username != null and username != ''"> username = #{username} </when> <when test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </when> <when test="userCity != null and userCity != ''"> and user_city = #{userCity} </when> </choose> </where> </select>
set
set タグは更新操作に使用され、パラメーターの選択に基づいて SQL ステートメントを自動的に生成します。 インターフェイスは次のように定義されています
public int updateUser(User user);
インターフェイスに対応する Mapper.xml 定義は次のとおりです
<update id="updateUser" parameterType="com.example.mybatis.entity.User"> update user <set> <if test="username != null and username != ''"> username=#{username}, </if> <if test="userEmail != null and userEmail != ''"> user_email=#{userEmail}, </if> <if test="userCity != null and userCity != ''"> user_city=#{userCity}, </if> <if test="age != null"> age=#{age} </if> </set> where id=#{id} </update>
#
接口定义如下所示
public List<User> getUsersByIds(List<Integer> ids);
接口对应的 Mapper.xml 定义如下所示
<!-- collection: 指定要遍历的集合 默认情况下 如果为Collection类型的,key为collection; 如果为List类型的,key为list 如果是数组类型,key为array 可以通过@Param("ids")来指定key item: 将当前遍历的元素赋值给指定的变量 open: 给遍历的结果添加一个开始字符 close: 给遍历的结果添加一个结束字符 separator: 每个元素之间的分隔符 --><select id="getUsersByIds" resultType="com.example.mybatis.entity.User"> select * from user where id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach></select>
用于批量插入
接口定义如下所示
public int addUserList(List<User> users);
接口对应的 Mapper.xml 定义如下所示
<insert id="addUserList" parameterType="com.example.mybatis.entity.User"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--返回自增主键--><insert id="addUserList" parameterType="com.example.mybatis.entity.User" useGeneratedKeys="true" keyProperty="id"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--还可以这样写--><!-- 这种方式需要数据库连接属性设置allowMultiQueries=true 这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除 --><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" collection="list" separator=";"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--如果是Oracle数据库,则需要这样写--><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" open="begin" close="end;" collection="list"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}); </foreach></insert>
以上がMyBatis動的SQLを学ぶの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック

HQL と SQL は Hibernate フレームワークで比較されます。HQL (1. オブジェクト指向構文、2. データベースに依存しないクエリ、3. タイプ セーフティ)、SQL はデータベースを直接操作します (1. データベースに依存しない標準、2. 複雑な実行可能ファイル)。クエリとデータ操作)。

「OracleSQLでの除算演算の使用方法」 OracleSQLでは、除算演算は一般的な数学演算の1つです。データのクエリと処理中に、除算演算はフィールド間の比率を計算したり、特定の値間の論理関係を導出したりするのに役立ちます。この記事では、OracleSQL での除算演算の使用法を紹介し、具体的なコード例を示します。 1. OracleSQL における除算演算の 2 つの方法 OracleSQL では、除算演算を 2 つの異なる方法で実行できます。

Oracle と DB2 は一般的に使用される 2 つのリレーショナル データベース管理システムであり、それぞれに独自の SQL 構文と特性があります。この記事では、Oracle と DB2 の SQL 構文を比較し、相違点を示し、具体的なコード例を示します。データベース接続 Oracle では、次のステートメントを使用してデータベースに接続します: CONNECTusername/password@database DB2 では、データベースに接続するステートメントは次のとおりです: CONNECTTOdataba

MyBatis 動的 SQL タグの解釈: Set タグの使用法の詳細な説明 MyBatis は、豊富な動的 SQL タグを提供し、データベース操作ステートメントを柔軟に構築できる優れた永続層フレームワークです。このうち、Set タグは、UPDATE ステートメントで SET 句を生成するために使用され、更新操作でよく使用されます。この記事では、MyBatis での Set タグの使用法を詳細に説明し、特定のコード例を通じてその機能を示します。 SetタグとはMyBatiで使用するSetタグです。

解決策: 1. ログインしているユーザーがデータベースにアクセスまたは操作するための十分な権限を持っているかどうかを確認し、ユーザーが正しい権限を持っているかどうかを確認します; 2. SQL Server サービスのアカウントに指定されたファイルまたはデータベースにアクセスする権限があるかどうかを確認します。 3. 指定されたデータベース ファイルが他のプロセスによって開かれているかロックされているかどうかを確認し、ファイルを閉じるか解放して、クエリを再実行します。管理者として試してください。Management Studio をなどとして実行します。

データベース技術コンテスト: Oracle と SQL の違いは何ですか?データベース分野では、Oracle と SQL Server の 2 つは非常に評判の高いリレーショナル データベース管理システムです。どちらもリレーショナル データベースのカテゴリに属しますが、両者の間には多くの違いがあります。この記事では、Oracle と SQL Server の違い、実際のアプリケーションにおけるそれらの機能と利点について詳しく説明します。まず、Oracle と SQL Server の間には構文に違いがあります。

MyBatisGenerator は、MyBatis が公式に提供するコード生成ツールで、開発者がデータベース テーブル構造に準拠した JavaBeans、Mapper インターフェイス、および XML マッピング ファイルを迅速に生成するのに役立ちます。コード生成に MyBatisGenerator を使用するプロセスでは、構成パラメーターの設定が重要です。この記事では、構成パラメータの観点から開始し、MyBatisGenerator の機能を詳しく説明します。

MyBatis のキャッシュ メカニズムの分析: 1 次キャッシュと 2 次キャッシュの違いと応用 MyBatis フレームワークでは、キャッシュはデータベース操作のパフォーマンスを効果的に向上させることができる非常に重要な機能です。そのうち、一次キャッシュと二次キャッシュは、MyBatis でよく使用される 2 つのキャッシュ メカニズムです。この記事では、一次キャッシュと二次キャッシュの違いと用途を詳細に分析し、具体的なコード例を示して説明します。 1. レベル 1 キャッシュ レベル 1 キャッシュはローカル キャッシュとも呼ばれ、デフォルトで有効になっており、オフにすることはできません。 1次キャッシュはSqlSesです
