プロジェクトのビジネスニーズが異なるため、データテーブル(動的テーブルビルディング、操作テーブルフィールドなど)を動的に操作する必要がある場合があります。一般的に、ログ、デバイスのリアルタイム位置情報などをデータテーブルに保存し、一定の期間、log_201806、log_201807などでストレージ用のテーブルを生成します。ここでは、Mybatisを使用して実装し、動的SQLが使用されます。
動的SQLは、MyBatisの強力な機能の1つです。 SQLステートメントを事前コンパイルする前に、MyBatisはSQLを動的に解析し、BoundSQLオブジェクトに解析します。これは、ここで動的なSQLを処理するためにも使用されます。
動的なSQL解析では、#{}と$ {}の効果は異なります。
#{} jdbc precompiledステートメントのパラメーターマーカーに解析されました。
次のSQLステートメントなど:
select * fromユーザーwhere name =#{name};次のように解析されます
select * fromユーザーwhere name =?;;
#{}がパラメータープレースホルダーに解析されているのがわかりますか? 。
$ {}は単なる純粋な文字列置換であり、動的なSQL解析段階で可変交換が実行されます。
次のSQLステートメントなど:
select * fromユーザーwhere name = $ {name};パラメーター「Joanna」を渡すと、SQLは次のように解析します。
select * fromユーザーwhere name = "joanna";
Precompilationの前にSQLステートメントに変数名が含まれていないことがわかります。
要約すると、$ {}の変数の交換段階は動的なSQL解析段階にあり、#{}の変数の置換はDBMSにあります。
以下は、MyBatisテーブルの動的な作成を実装し、テーブルが存在するかどうかを決定し、テーブル関数を削除します。
mapper.xml
<?xml version = "1.0" encoding = "utf-8"?> <!doctype mapper public " - // mybatis.org//dtd mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" namespace = "xx.xxx.xx.mapper.operateTablemapper"> <select id = "exptable" parametertype = "string" resulttype = "integer"> select count(*)from information_schema.tables where lcase(table_name)=#{existcable} </select <uppreatt <repate $ {tableName} </update> <update id = "createNewtable" parametertype = "string"> create table $ {tablename}(id bigint(20)null auto_increment、not null、null、dx double null null、dy doubl not null、dz double not not not not not not not null、 null、speed floatデフォルトnull、方向フロートデフォルトnull、属性varchar(255)デフォルトnull、プライマリキー(id))</update> <inserce id = "insert" parametertype = "xx.xxx.xx.po.trackpoint"> $ {tablename}に挿入} (#{trackpoint.entityId}、#{trackpoint.dx}、#{trackpoint.dy}、#{trackpoint.dz}、#{trackpoint.ntype}、#{trackpoint.gnsstime}、#{trackpoint.speed}、#{trackpoint.direction}、#direction}mapper.java
パッケージxx.xxx.xx.mapper;
Import org.apache.ibatis.annotations.param; import xx.xxx.xx.po.trackpoint; public interface operateTablemapper {int custable(string tablename); int droptable(@param( "tablename")string tablename); int createNewtable(@param( "tablename")string tablename); int insert(@param( "tablename")string tablename、@param( "trackpoint")trackpointトラックポイント);}要約します
上記は、編集者が紹介したMyBatis Dynamic Creationテーブルの例です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!