MyBatisの強力な特徴の1つは、通常、その動的なSQL機能です。 JDBCまたは他の同様のフレームワークを使用した経験がある場合、SQLストリングを条件付きで連結することがどれほど痛いかを理解してください。リストの最後にスペースを忘れたり、コンマを省略したりできないことを確認してください。動的SQLはこの痛みを徹底的に処理できます。
動的sql
MyBatisの動的SQLは、SQL Stringスプライシングの痛みを解決します。
1.if
<select id = "findactiveblogwithtitlike" parametertype = "blog" resultType = "blog"> select * from blogwhere state = 'active' <if test = "title '> and title' like#{title} </if> </select>この文は、オプションのテキスト検索機能を提供します。タイトルが渡されない場合、アクティブ化されたすべてのブログが返されます。
タイトルが渡された場合、同様のタイトルが見つかります。
2
<select id = "findactivebloglike" parametertype = "blog" resulttype = "blog"> select * from blog where <choice> <when test = "title =" title!= null "> and#{title} </when>" when> "author!= null and author.name!= null"> 1 </それ以外の> </chood> </select>注:上記の条件が一致しない場合、それはブログからselect *になります
2番目の一致しかない場合、それはSelect *からSelect * from BlogからSomelikeのようになります
明らかに、これはクエリで失敗します。この問題を解決するために、MyBatisは解決策を提供します。
<select id = "findactivebloglike" parametertype = "blog" resulttype = "blog"> select * from blog where <triam freix = "where" prefixoverrides = "and | or"> <choice> <when test = "title!= null"> #{author.name} </when> <それを科されて> foture = 1 </それ以外の> </chood> </trim> </select>オーバーライドプロパティは、パイプテキストセパレーターでオーバーライドされており、ここでは空白スペースが重要です。その結果、Inrertextでオーバーライドで指定されたコンテンツを削除します。
3.セット
<update id = "updateauthorifn exmineary" parametertype = "author"> update olth <set> <if test = "username!= null"> username =#{username}、</if> <if> <if> "> null"> password =#{passwors id =#{id} </update>最適化後、上記と同じ問題:
<update id = "updateauthorifn exmineary" parametertype = "author"> update author <trim refix = "where" prefixoverrides = "、"> <set> <if test = "username!= null"> username}、</if> <if> <if> "null" null "> email =#{email} </if> </set>ここで、id =#{id} </trim> </update>上記は、編集者が紹介したSQL文字列のMyBatis動的スプライシングの問題です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!