MyBatis
MyBatis設定
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.4'
spring:
datasource:
driver-class-name: org.postgresql.Driver
jdbc-url: jdbc:postgresql://localhost/mybatis
username: test
password: test@@
mybatis:
# 패키지 명을 생략할 수 있도록 alias 설정
type-aliases-package: com.mybatis.dto
# mapper.xml 위치 지정
mapper-locations: mybatis-mapper/**/*.xml
# model 프로퍼티 camel case 설정
configuration.map-underscore-to-camel-case=true
# mapper 로그레벨 설정
logging:level:com:atoz_develop:mybatissample:repository=DEBUG
Mapper XMLファイル
cache
:名前空間のキャッシュを設定cache-ref
:他のネーミングスペースのキャッシュ設定resultMap
:データベース結果データをオブジェクトにロードする方法を定義する別名sql
:他の構文の再利用に使用されるSQLセグメントinsert
:マッピングされたINSERT構文update
:マッピングされたUPDATE構文delete
:マッピングされたDELETE構文select
:マッピングされたSELECT構文SELECT
<select id="selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>
->この構文の名前はselectPersonで、intタイプのパラメータがあります.そして、結果データはHashMapに格納される.パラメータ記号:#{id}
この記号は、マイワティスが予備状態パラメータを作成することを示します.JDBCを使用すると、PreparedStatementに「?」と表示されます.パラメータは形式で渡されます.すなわち、上記の設定の動作原理は以下の通りである.
// JDBC 코드와 유사함
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);
<select
id="selectPerson"
parameterType="int"
resultType="hashmap"
resultMap="personResultMap"
flushCache="false"
useCache="true"
timeout="10"
fetchSize="256"
statementType="PREPARED"
resultSetType="FORWARD_ONLY">
ツールバーの説明:
id
ネーミングスペースで文法を検索するために使用できる唯一の区切り文字
parameterType
構文に渡すパラメータのパッケージパスを含む完全なクラス名または別名.
resultType
この構文で返される所望のタイプのパケットパスを含む完全なクラス名または別名.
resultMap
外部resultMapの参照名
flushCache
この値をtrueに設定すると、構文が呼び出されるたびにローカルキャッシュと2次キャッシュが消去されます.(flush)のデフォルト値はfalseです.
useCache
この値をtrueに設定すると、構文の結果は2番目のレベルのキャッシュにキャッシュされます.デフォルトはtrueです.
timeout
例外を放出する前にデータベース要求の結果を待つ最大時間を設定します.デバッガは設定されていません.ドライバによってはサポートされていない場合があります.
fetchSize
指定した数の結果を返すドライバプロンプト形式の値を許可します.デバッガは設定されていません.ドライバによってはサポートされていない場合があります.
statementType
STATEMENT、PREPAREDまたはCALLABLEを選択できます.マイワティスにState、PreparedStateまたはCallableStateを使用させます.デフォルトはPREPAREDです.
INSERT, UPDATE AND DELETE
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
keyColumn=""
useGeneratedKeys=""
timeout="20">
<update
id="updateAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementTypes="PREPARED"
timeout="20">
<delete
id="deleteAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
ツールバーの説明:
id
ネーミングスペースで文法を検索するために使用できる唯一の区切り文字
parameterType
構文に渡すパラメータのパッケージパスを含む完全なクラス名または別名.
flushCache
この値をtrueに設定すると、構文が呼び出されるたびにキャッシュが消去されます.デフォルトはfalse
timeout
例外を放出する前にデータベース要求の結果を待つ最大時間を設定します.デバッガは設定されていません.ドライバによってはサポートされていない場合があります.
statementType
STATEMEENT、PREPARED、CALLABLEから選択できます.マイワティスにState、PreparedStateまたはCallableStateを使用させます.デフォルトはPREPAREDです.
useGeneratedKeys
(入力(insert,update)では、データベース内で生成されたキー(MySQLやSQLサーバなど)を受信するJDBC getGenerated Keyメソッドを使用するように設定されています.デフォルトはfalseです.
keyProperty
(入力(insert,update)getGeneratedKeysメソッドまたはinsert構文を設定するselectKeyサブエレメントから返される鍵を指定するプロファイルのみ
keyColumn
(「入力」(insert,update)にのみ適用され、生成キーを持つテーブルのカラム名を設定します.キーバーテーブルは最初のバーのデータベースではありません(P
<insert id="insertAuthor">
insert into Author (id, username, password, email, bio)
values (#{id}, #{username}, #{password}
</insert>
<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>
使用するデータベースがMySQLやSQLサーバなどの自動鍵生成をサポートしている場合は、userGeneratedKeys=「true」を「userGeneratedKeys=」に設定し、ターゲット・プログラムでkeyPropertyを設定できます.たとえば、Authorテーブルがid列に自動生成キーを適用した場合、構文は次のようになります.<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
insert into Author (username, password, email, bio)
values (#{username},#{password},#{email},#{bio})
</insert>
使用するデータベースが複数のレコード入力をサポートしている場合は、Authorのリストまたは配列を渡すことができ、自動生成キーをインポートすることもできます.<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
insert into Author (username, password, email, bio) values
<foreach item="item" collection="list" separator=",">
(#{item.username}, #{item.password}
</foreach>
</insert>
MyBatis foreach文サポートラベル<select id="selectAuthor" resultType="com.test.Author">
select * from ttest where name in
<foreach collection='list' index='index' item='abc' open='(' close=')' separator=','>
#{abc}
</foreach>
</select>
アレイ時<select id="selectAuthor" resultType="com.test.Author">
select * from ttest where name in
<foreach collection='array' index='index' item='abc' open='(' close=')' separator=','
#{abc}
</foreach>
</select>
マイワティスは、キー列の自動生成をサポートしていない他のデータベースにも他の方法を提供しています.この例では、ランダムIDを生成しています.
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email, bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection, jdbcType=VARCHAR})
</insert>
->selectKey構文が最初に実行され、author id propertyに設定されます.次にinsert構文を実行します.<selectKey
keyProperty="id"
resultType="int"
order="BEFORE"
statementType="PREPARED">
ツールバーの説明:
keyProperty
selectKey構文の結果を設定するターゲットプロファイル
keyColumn
戻った結果、3人の列名はプロ選手と一致した.複数のコラムを使用すると、リストはカンマで区切られます.
resultType
結果タイプ
order
BEFOREまたはAFTERを設定できます.BEFOREに設定されている場合は、まず鍵を問合せ、その値をkeyPropertyに設定し、挿入構文を実行します.AFTERに設定するとINSERT文が実行され、selectKey文が実行されます.
statementeType
STATEMENT、PREPARED、CALLABLEの構文タイプをサポートし、STATENT、PREPSTATEM、CALLABLEをマッピングします.
@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);
@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);
@Select("select * from user where email = #{email}")
User findByEmail(@Param("email") String email);
you can just write:@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
in which the ${column} will be substituted directly and the #{value} will be "preapred"User userOfId1 = userMapper.findByColumn("id", 1L);
User userOfNameKid = userMapper.findByColumn("name", "kid");
User userOfEmail = userMapper.findByColumn("email", "[email protected]");
Result Maps
<!-- XML 설정파일에서 -->
<typeAlias type="com.test.model.User" alias="User"/>
<resultMap id="detailedBlogResultMap" type="Blog">
<constructor>
<idArg column="blog_id" javaType="int" />
</constructor>
<result property="title" column="blog_title" />
<association property="author" javaType="Author">
<id property="id" column="author_id" />
<result proeprty="username" column="author_username"/>
<result property="password" column="author_password"/>
</association>
<collection property="posts" ofType="Post">
<id property="id" column="post_id" />
<result property="author" javaType="Author"/>
<discriminator javaType="int" column="draft">
<case value="1" resultType="DraftPost"/>
</discriminator>
</collection>
</resultMap>
resultMap
- id: 추후 쿼리를 정의하는 태그에서 resultType 대신 사용될 resultMap argument의 value가 될 것이다.
constructor
- 생성자이다. 위 예제에서는 id만 이용하고 있는데 이 경우에는 Blog(int blog_id) 꼴의 생성자를 호출할 것이다.
result
- 결과값의 column을 자바 클래스의 어떤 멤버 변수에 할당할 것인지 정의한다.
association
- has one일 때 사용하는 태그
collection
- has many일 때 사용하는 태그
<discriminator javaType="int" column="vehicle_type">
<case value="1" resultMap="carResult" />
<case value="2" resultMap="vanResult" />
</discriminator>
->vehicle typeという名前のカラムの値をcase値と比較し、同じ値のresultMapに一致させます.<resultMap id="blogResult" type="Blog">
<association property="author" column="author_id" javaType="Author" select="selectAuthor" />
</resultMap>
<select id="selectBlog" resultMap="blogResult">
select * from blog where id = #{id}
</select>
<select id="selectAuthor" resultType="Author">
select * from author where id = #{id}
</select>
上の例の動作1.selectBlogのクエリselect from blog.id=#{id}です.
2.成果物をblogResultにマッピングします.
3.author id列-authorメンバー変数以外の列とメンバー変数が自動的に一致します.
4.authorを入力するには、select=「selectAuthor」を実行します.
5.id=#{id}のselectAuthorを実行するselect from author.(このときblogResultのassociationで指定した列author idがIDとして自動的に使用されます.)
6.結果値を使用してauthor javabinを生成し、blog javabinに設定します.
Reference
この問題について(MyBatis), 我々は、より多くの情報をここで見つけました https://velog.io/@bey1548/MyBatisテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol