1。MyBatisの紹介
MyBatisは、プレーンSQLクエリ、ストアドプロシージャ、高度なマッピングをサポートする優れた永続レイヤーフレームワークです。
MyBatisは、ほぼすべてのJDBCコードとパラメーターの手動設定と、結果セットの検索カプセル化を排除します。
MyBatisは、構成と生のマッピングにシンプルなXMLまたはアノテーション、マッピングインターフェイス、JavaのPOJO(プレーンオールドJavaオブジェクト)をデータベースのレコードに使用できます。
jdbc-> dbutils(auto -capsulation) - > mybatis-> hibernate
MyBatisはXMLにSQLを書き込み、データベースにアクセスします。
2。MyBatisを始めましょう
2.1。新しいJavaプロジェクトを作成します
mybatisとmysqlドライバーのjar:mybatis-3.1.1.jar、mysql-connector-java-5.1.7-bin.jar
2.2。新しいテーブルを作成します
MyBatisを作成します。MyBatisを使用します。テーブルユーザーを作成します(ID int primary key auto_increment、name varchar(20)、age int); inserting into users(name、age)values( 'tom'、12); inserting users(name、age)values( 'jack'、11);
2.3。 mybatis構成ファイルconf.xmlを追加します
<?xml version = "1.0" encoding = "utf-8"?> <!doctype構成public " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd" ID = "Development"> <transactionManager Type = "JDBC" /> <DataSource Type = "> <プロパティ名="ドライバー "value =" com.mysql.jdbc.driver " /> <プロパティ名=" url "url" value = "jdbc:mysql:// localhost:propertyhost:3306 /mybatis" /> < name = "password" value = "root"/> </dataSource> </environment> </environments> </configuration>
2.4。テーブルに対応するエンティティクラスを定義します
パブリッククラスユーザー{private int id; private string name; private int age; // get、set method}2.5。ユーザーテーブルを操作するSQLマッピングファイルusermapper.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 = "com.atguigu.mybatis_test.test1.usermapper"> <select id = "getuser" parametertype = "int" resulttype = "com.atguigu.mybatis_test.test1.user"> select *ユーザーWhere id =#{id} </select> </mapper2.6。 conf.xmlファイルにusermapper.xmlファイルを登録します
<mappers> <mapper resource = "com/atguigu/mybatis_test/test1/usermapper.xml"/> </mappers>
2.7。テストコードの作成:定義された選択ステートメントを実行します
パブリッククラステスト{public static void main(string [] args)throws ioexception {string resource = "conf.xml"; // mybatisの構成ファイルをロードする(関連するマッピングファイルもロード)リーダー= resources.getResourceasReader(リソース); sqlSessionFactoryBuilder()。ビルド(Reader); //マッピングfile = sessionFactory.opensession(); //マッピングSQL String Stringステートメント= "com.atguigu.mybatis.batis.bean.bean.beant"+execute "+execute" sqluser user = session.selectone(ステートメント、1); system.out.println(user);}}}3.ユーザーテーブルのCrudを操作します
3.1.xml実装
3.1.1。 SQLマッピングXMLファイルを定義します。
<ID = "Insertuser" parametertype = "com.atguigu.ibatis.user"> inserting users(name、age)values(#{age}、#{age}); </inserte> <deleteuser "parametertype =" int " parametertype = "com.atguigu.ibatis.bean.user">更新ユーザーset name =#{name}、age =#{age} where id = {id} </update> <select id = "selectuser" parametertype = "int" resulttype = "com.atguigu.ibatis.batis.Bigean"> id =#{id} </select> <select id = "selectalusers" resulttype = "com.atguigu.ibatis.bean.user"> select * fromユーザー</select>3.1.2。このマッピングファイルをconfig.xmlに登録します
<mapper resource = "com/atguigu/ibatis/bean/usermapper.xml"/>
3.1.3。ダオで呼ばれます
public user getUserbyId(int id){sqlsession session = sessionfactory.opensession(); user user = session.selectone(uri+"。selectuser"、id); return user;}3.2。注釈の実装
3.2.1。 SQLマッピングのインターフェイスを定義します
パブリックインターフェイスusermapper {@insert( "ユーザー(name、age)values(#{name}、#{age})")public int insertuser(user user);@delete( "delete from users =#{id}」 id =#{id} ")public int updateUser(user user);@select(" select * from users where users where where where where where where where where where where where where where where where id);@select( "select * from users")public list <user> getAlluser();}3.2.2。このマッピングインターフェイスを構成に登録します
<mapper/>
3.2.3。ダオで呼ばれます
public user getUserbyId(int id){sqlsession session = sessionfactory.opensession(); usermapper mapper = session.getmapper(usermapper.class); user user = mappper.getuserbyid(id); return user;}4.最適化できるいくつかの場所
4.1。データベースに接続するための構成は、プロパティファイルに個別に配置できます。
## db.properties <br> <プロパティリソース= "db.properties" /> <プロパティ名= "driver" value = "$ {driver}" /> <プロパティ名= "url" value = "$ {url}" /> <プロパティ名= "username" value = "$ {username}"4.2。エンティティクラスのエイリアスを定義し、SQLマッピングXMLファイルの参照を簡素化する
<TypeAliase> <TypeAlias Type = "com.atguigu.ibatis.user" alias = "_ user"/> </typealiase>
4.3。 srcの下にlog4j構成ファイルを追加して、ログ情報を印刷できます
1.瓶を追加:
log4j-1.2.16.jar
2.1。 log4j.properties(方法1)
log4j.properties、log4j.rootlogger = debug、console#consolelog4j.appender.console = org.apache.log4j.consoleappenderlog4j.appender.console.layout = org.apache.log4j.patternlayoutlog4j.Appender.console.lyut.conutes %-5p [%c] - %nlog4j.logger.java.sql.resultset = infolog4j.logger.org.apache = infolog4j.logger.java.sql.connection = debuglog4j.logger.java.sql.statement = debuglog4j.loggar.java.java.sql.prepadement = debuglog4j.
2.2。 log4j.xml(方法2)
<?xml version = "1.0" encoding = "utf-8"?> <!doctype log4j:構成システム "log4j.dtd"> <log4j:configuration xmlns:log4j = "http://jakarta.apache.org/log4j/" value = "%-5p%d {mm-dd hh:mm:ss、ss}%m(%f:%l) /n" /> < /layout> < /appender> <logger name = "java.sql"> <level value = "debug" /> < /logger> <logger nam /> < /logger> <root> <level value = "debug" /> <appender-ref ref = "stdout" /> < /root> < /log4j:configuration>5。フィールド名とエンティティクラス属性名の間の競合を解決する
5.1。テーブルとフィールドを準備します
テーブルオーダーを作成します(Order_id int primary key auto_increment、order_no varchar(20)、order_price float);挿入注文(order_no、order_price)値( 'aaaa'、23)
5.2。エンティティクラスを定義します
パブリッククラス注文{private int id; private string orderno; private float価格;}5.3。 GetOrderByID(ID)のクエリを実装してください:
方法1:SQLステートメントのエイリアスを定義します
<select id = "selectorder" parametertype = "int" resultType = "_ order"> selece order_id id、order_no orderno、order_price rice from orders_id =#{id} </select>方法2:<resultmap>から
<select id = "selectorderresultmap" parametertype = "int" resultmap = "orderresultmap"> select * select * where orders_id =#{id} </select> <resultmap type = "_ order" id = "orderresultmap"> <id property = "id" columm = "order =" result propertion = "colummo"/> <"columm列= "order_price"/> <result property = "price" column = "order_price"/> <resultmap>6.アソシエーションテーブルクエリを実装します
6.1。 1対1の関連付け
6.1.1。要件を提案します
クラスIDに基づくクラス情報をクエリします(教師との情報)
6.1.2。テーブルとデータを作成します
テーブルティーチャー(T_ID INTプライマリキーAUTO_INCREMENT、T_NAME VARCHAR(20)); CREATE TABLEクラス(C_ID INTプライマリキーAuto_Increment、C_Name Varchar(20)、Teacher_id int); Alter Table Class constraint fk_teacher_id外部キー(Teacher_id)参照教師(t_id);教師(t_name)値( 'ls1');挿入教師(t_name)値( 'ls2'); class(c_name、teacher_id)values( 'bj_a'、1); class(c_name、teacher_id)values( 'bj_b'、2);
6.1.3。エンティティクラスの定義:
パブリッククラス教師{private int id; private string name;} public class classes {private int id; private string name; private teacher teacher;}6.1.4。 SQLマッピングファイルclassmapper.xmlを定義します
< c.teacher_id = t.t_id and c.c_id = s.class_id and c.c_id = 1-> <select id = "getClass3" parameterType = "int" resultmap = "classResultmap3"> select * from class c、from Student s、where c.teacher_id = t.t_id and c.c_id = s.class_id and c.c_id =#{id} </select> <resultmap type = "_ classes" id "id =" classResultmap3 "> <id property =" id "column =" c_id "/> <resput property =" name "column =" c_id "/> <associationプロパティ=" column "column =" forter_id "javatype =" "_" ">" colum列= "t_name"/> <resultプロパティ= "name" column = "t_name"/> </associate> <ネストされたクエリ:別のsqlマッピングステートメントを実行して、予想される複雑なタイプを返しますselect * from class * from co_id = 1; select * t_id = 1 // 1は、class_id = 1 // 1から取得した先生の値です。 resultmap = "classResultmap4"> select * class c_id =#{id} </select> <resultmap type = "_ classesresultmap4"> <id property = "id" column = "c_id"/> <resputプロパティ= "name" column = "c_name"/> <colums = "" column_id " select = "getTeacher2"> </associate> <collectionプロパティ= "sustent" ofType = "_ dulicle =" c_id "select =" getStudent "> </collection> </resultmap> </resultmap> <select id =" getTeacher2 "getTeacher2" getTeacher2 "getTeacher2" getTeacher2 "getTeacher2" getTeacher2 " id = "getStudent" parametertype = "int" resultType = "_ desute"> select s_id id、s_name name from Student where class_id =#{id} </select>6.1.5。テスト
@testpublic void testoo(){sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone( "com.atguigu.day03_mybatis.test5.oomapper。 = Factory.opensession(); classes c = sqlsession.selectone( "com.atguigu.day03_mybatis.test5.oomapper.getclass2"、1); system.out.println(c);}6.2。 1対多くの協会
6.2.1。要件を提案します
学生や教師を含むClassIDによると、対応するクラス情報を照会する
6.2.2。テーブルとデータの作成:
テーブル学生(S_ID INTプライマリキーAUTO_INCREMENT、S_NAME VARCHAR(20)、class_id int); inserting into Student(s_name、class_id)values( 'xs_a'、1); inserting intout interuste(s_name、class_id)values( 'xs_b'、1); inserting interine(s_name、insert intering(s_name); class_id)values( 'xs_d'、2); insert into into into intoud(s_name、class_id)values( 'xs_e'、2); inserting into intount student(s_name、class_id)values( 'xs_f'、2);
6.2.3。エンティティクラスを定義します
パブリッククラスの学生{private int id; private string name;} public class classes {private int id; private string name; private teacher teacher; private list <sustent> sustent;}6.2.4。 SQLマッピングファイルclassmapper.xmlを定義します
< c.teacher_id = t.t_id and c.c_id = s.class_id and c.c_id = 1-> <select id = "getClass3" parameterType = "int" resultmap = "classResultmap3"> select * from class c、from Student s、where c.teacher_id = t.t_id and c.c_id = s.class_id and c.c_id =#{id} </select> <resultmap type = "_ classes" id "id =" classResultmap3 "> <id property =" id "column =" c_id "/> <resput property =" name "column =" c_id "/> <associationプロパティ=" column "column =" forter_id "javatype =" "_" ">" colum列= "t_name"/> <resultプロパティ= "name" column = "t_name"/> </associate> <ネストされたクエリ:別のsqlマッピングステートメントを実行して、予想される複雑なタイプを返しますselect * from class * from co_id = 1; select * t_id = 1 // 1は、class_id = 1 // 1から取得した先生の値です。 resultmap = "classResultmap4"> select * class c_id =#{id} </select> <resultmap type = "_ classesresultmap4"> <id property = "id" column = "c_id"/> <resputプロパティ= "name" column = "c_name"/> <colums = "" column_id " select = "getTeacher2"> </associate> <collectionプロパティ= "sustent" ofType = "_ dulicle =" c_id "select =" getStudent "> </collection> </resultmap> </resultmap> <select id =" getTeacher2 "getTeacher2" getTeacher2 "getTeacher2" getTeacher2 "getTeacher2" getTeacher2 " id = "getStudent" parametertype = "int" resultType = "_ desute"> select s_id id、s_name name from Student where class_id =#{id} </select>6.2.5。テスト
@testpublic void testom(){sqlsession sqlsession = factory.opensession(); classes c = sqlsession.selectone( "com.atguigu.day03_mybatis.test5.oomapper.getclass3"、1); system.out.println(c);}@testpublic void void void sqlsession = factory.opensession(); classes c = sqlsession.selectone( "com.atguigu.day03_mybatis.test5.oomapper.getclass4"、1); system.out.println(c);}7。動的SQLおよびファジークエリ
7.1。要件
マルチコンディショナルクエリユーザー(名前ファジーマッチング、指定された最小値と最大値の間の年齢)を実装します。
7.2。データベースとテーブルを準備します
テーブルd_user(id int primary key auto_increment、name varchar(10)、age int(3)); inserting into d_user(name、age)values( 'tom'、12); d_user(name、age)values( 'bob'、13)に挿入します。 d_user(name、age)values( 'jack'、18); 7.3.conditionuser(query条件付きエンティティクラス)private string name; private int minage; private int maxage;
7.4.ユーザーテーブルエンティティクラス
Private int id; private string name; private int age;
7.5.usermapper.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"> <mapper namespace = "com.atguigu.day03_mybatis.test6.usermapper"> <select id = "getuser" parametertype = "com.atguigu.day03_mybatis.test6.conditionuser" resulttype = "com.atguigu.day03_mybatis.test6.test. age> =#{minage} and age <=#{maxage} <if test = 'name!= "%null%"'>およびname 'like#{name} </if> </select> </mapper>7.6.USERTEST(テスト)
public class usertest {public static void main(string [] args)throws ioexception {reader reader = resources.getResourceasReader( "conf.xml"); sqlsessionFactoryFactory = new sqlsessionFactoryBuilder()。 "com.atguigu.day03_mybatis.test6.usermapper.getuser"; list <user> list = sqlsession.selectlist(statement、new ConditionUser( "%a%"、1、12)); System.out.println(list);}}}MyBatisで利用可能な動的SQLタグ
8。ストアドプロシージャの呼び出し
8.1。需要があります
入っている人が0の場合、女性の数を照会します。そうでなければ男性
8.2。データベーステーブルとストアドプロシージャを準備します。
テーブルp_user(id int primary key auto_increment、name varchar(10)、sex char(2)); inserting p_user(name、sex)values( 'a'、 "male"); p_user(name、sex)values( 'b'、 "female")に挿入; p_user(name、sex)values( 'c'、 "male")に挿入; #createストアドプロシージャ(入っている人が0の場合は男性または女性の数を求めてください、女性は男性です)delimiter $ delimiter $ create mybatis.ges_user_count(in sex_id int、out user_count int) mybatis.p_user p_user.sex = 'male' into user_count; end if; end $#call stored procedure delimiter; set @user_count = 0; call mybatis.ges_user_count(1、@user_count); @user_countを選択;
8.3。テーブルのエンティティクラスを作成します
public classユーザー{private string id; private string name; private string sex;}8.4.usermapper.xml
<mapper namespace = "com.atguigu.mybatis.test7.usermapper"> <! - クエリは男性または女性の数を取得します。受信が0の場合、女性はそうでなければ男性です。callmybatis.get_user_count(1、@user_count); - > <select id = "getCount" statementType = "callable" parametermap = "getCountMap"> call mybatis.get_user_count(? id = "getCountMap"> <parameter Property = "sex_id" mode = "in" jdbctype = "integer"/> <parameterプロパティ= "user_count"モード= "out" jdbctype = "integer" // </parametermap> </mapper>
8.5。テスト
map <string、integer> parammap = new hashmap <>(); parammap.put( "sex_id"、0); session.selectone(statement、parammap); integer usercount = parammap.get( "user_count"); system.out.println(usercount);
9。MyBatisキャッシュ
9.1。 mybatisキャッシュを理解します
ほとんどの持続層フレームワークと同様に、MyBatisはL1およびL2キャッシュのサポートも提供します。
1。レベル1キャッシュ:HashMap repetualCacheに基づいてローカルキャッシュ、そのストレージスコープはセッションです。セッションがフラッシュまたは閉じた後、セッション内のすべてのキャッシュがクリアされます。
2。二次キャッシュのメカニズムは、プライマリキャッシュのメカニズムと同じです。デフォルトでは、PerpetualCacheおよびHashMapストレージも使用します。違いは、そのストレージスコープがマッパー(名前空間)であり、ehcacheなどのストレージソースをカスタマイズできることです。
3.キャッシュデータの更新メカニズムの場合、特定のスコープ(第1レベルのキャッシュセッション/セカンドレベルのキャッシュ名空間)がC/U/D操作で実行される場合、このスコープの下の選択のすべてのキャッシュはデフォルトでクリアされます。
9.2.mybatisレベル1キャッシュ
9.2.1。タスクに基づくクエリ
IDに基づいて対応するユーザーレコードオブジェクトをクエリします。
9.2.2。データベーステーブルとデータを準備します
テーブルC_USER(ID INT Primary Key Auto_Increment、Name Varchar(20)、age int); inserting into c_user(name、age)values( 'tom'、12); inserting into c_user(name、age)values( 'jack'、11);
9.2.3。テーブルのエンティティクラスを作成します
パブリッククラスのユーザーは、Serializable {private int id; private string name; private int age;9.2.4.usermapper.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 = "com.atguigu.mybatis.test8.usermapper"> <select id = "getuser" parametertype = "int" resulttype = "_ cuser"> select * from c_user where where where where where where where where where where where where where where age =#{age}ここで、id =#{id} </update> </mapper>9.2.5。テスト
/**レベル1キャッシュ:つまり、セッションレベルのキャッシュ(デフォルトで)*/@@testpublic void testcache1(){sqlsession session = mybatisutils.getsession(); string statemen 1); system.out.println(user);/**レベル1キャッシュはデフォルトで使用されます*//*user = session.selectone(statement、1); system.out.println(user);*//*1。同じセッションでなければなりません。セッションオブジェクトが閉じている場合()、それを使用することは不可能です*//*session = mybatisutils.getSession(); user = session.selectone(statement、1); system.out.println(user);*//*2。クエリ条件は同じ*//*user = session.selectone(statement、2); system.out.println(user);*//*3です。 session.clearcache()は、キャッシュをクリーニングするために実行されていません*//*session.clearcache(); user = session.selectone(statement、2); system.out.println(user);*//*4。追加、削除、変更された操作はありません(これらの操作はキャッシュをクリーンアップします)9.3.MyBatisレベル2キャッシュ
9.3.1。 usermapper.xmlに<cache>を追加します
<mapper namespace = "com.atguigu.mybatis.test8.usermapper"> <cache/>
9.3.2。テスト
/**テストレベル2キャッシュ*/@testPublic void testcache2(){stringステートメント= "com.atguigu.mybatis.test8.usermapper.getuser"; sqlsession session = mybatisutils.getsession(); user user = session.selectone(statem 1); session.commit(); system.out.println( "user ="+user); sqlsession session2 = mybatisutils.getsession(); user = session2.selectone(statement、1); session.commit(); system.out.println( "user2 ="+user);};}9.3.3。補足ノート
1.マッピングステートメントファイルのすべての選択ステートメントがキャッシュされます。
2。ステートメントファイルのすべての挿入、更新、および削除されたすべての挿入、更新、および削除キャッシュが更新されます。
3.キャッシュは、最近使用されていない(LRU、最近使用されていない)アルゴリズムを使用して再試行されます。
4.キャッシュは、指定された時間間隔に従って更新されます。
5.キャッシュは1024オブジェクトを保存します
<cacheeviction = "fifo" //リサイクル戦略はファーストイン、ファーストアウトFlushinterval = "60000" //自動更新時間60ssize = "512" // 512リファレンスオブジェクトreadonly = "true" // readone
10。スプリング統合mybatis
10.1。瓶を追加します
【マイバティス】
MyBatis-3.2.0.jar
mybatis-spring-1.1.1.jar
log4j-1.2.17.jar
【春】
spring-aop-3.2.0.Release.jar
Spring-Beans-3.2.0.Release.jar
Spring-Context-3.2.0.Release.jar
Spring-Core-3.2.0.Release.jar
Spring-Expression-3.2.0.Release.jar
Spring-JDBC-3.2.0.Release.jar
Spring-Test-3.2.4.Release.jar
Spring-TX-3.2.0.Release.jar
Aopalliance-1.0.jar
cglib-nodep-2.2.3.jar
commons-logging-1.1.1.jar
【MySQLドライバーパッケージ】
mysql-connector-java-5.0.4-bin.jar
10.2。データベーステーブル
テーブルs_user(user_id int auto_incrementプライマリキー、user_name varchar(30)、user_birthday date、user_salary double)を作成する
10.3。エンティティクラス:ユーザー
パブリッククラスユーザー{private int id; private string name; private date Birthday; private double Salary; // set、get method}10.4.daoインターフェイス:usermapper(xxxmapper)
public interface usermapper {void save(user user); void update(user user); void delete(int id); user findbyid(int id); list <user> findall();}10.5.SQLマッピングファイル:usermapper.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"> <mapper namespace = "com.atguigu.mybatis.test9.usermapper"> <resultmap type = "user" userresult "> <result column =" user_id "property =" id "/> <result column =" user_name "property =" name "/> <result column =" user_birrary "/" commantion = "forthang = < column = "user_salary" property = "salary"/> <resultmap> <! - データの挿入後にIDを取得 - > <id = "save" keycolumn = "user_id" keyproperty = "id" usegeneratedkeys = "true">挿入>挿入s_user(user_name、user_birthday、user_salary)values(#{name}、#{batirnd}、#{salary})</insert> <update id = "update"> update s_userset user_name =#{name}、user_birthday = {bashation} #{id} </update> <delete id = "delete"> delete from s_userwhere user_id =#{id} </delete> <select id = "findbyid" resultmap = "userresult"> select *from s_userwhere user_id =#{id} </select id = "resultmap =" userresul s_user </select> </mapper>10.6.Spring構成ファイル:beans.xml
<?xmlバージョン= "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:p = "http://ww.springframework. "xmlns:context =" http://www.springframework.org/schema/context "xmlns:tx =" http://www.springframework.org/schema/tx "xsi =" http:///www.springfr amework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context/sprin g-context-3.2.xsdhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <! - 1。データソース:DriverManagerDataSource-> <Bean Id = "DataSource" class = "org.springframework.jdbc.datasource.drivermanagerdatasource"> <プロパティname = "driverclassname" value = "com.mysql.jdbc.driver" value = "jdbc:mysql:// localhost:3306/mybatis"/> <property name = "username" value = "root"/> <property name = "password" value = "root"/> </bean> <! - 2。 MyBatisのsqlsession Factory:sqlsessionfactorybeandatasource / typealiasespackage-> <bean id = "sqlsessionfactory"> <プロパティ名= "dataSource" ref = "dataSource" /> <プロパティname = "Typealiasespackage" " value = "com.atigu.spring_mybatis2.domain"/> </bean> <! - 3。 MyBatisは自動的にスキャンしてSQLマッピングファイルをロードします:MapperScanConnoconFigurersQlSessionFactory/basePackage-> <bean> <bean> <property name = "basepackage" value = "com.atigu.spring_mybatis2.mapper"/>> <プロパティname = "管理:DataSourcetransactionManager - > <Bean Id = "Txmanager"> <Property name = "DataSource" Ref = "DataSource"/> </bean> <! - 5。
10.7.mybatis構成ファイル:mybatis-config.xml
<?xml version = "1.0" encoding = "utf-8"?> <!doctype configurationpublic " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"不要 - > <! - 外部構成ファイルを設定 - > <! - カテゴリ名を設定 - > <! - データベース接続環境を設定 - > <! - ファイルのマッピング - > </configuration>
10.8。テスト
@runwith(springjunit4classrunner.class)// springtestテストフレームワークを使用@contextconfiguration( "/beans.xml")//パブリッククラスsmtest {@autowired // inject private usermapper usermapper; @testpublic void() date()); user.setname( "mary"); user.setsalary(300); usermapper.save(user); system.out.println(user.getid();}@estublic void update(){user user = usermapper.findbyid(2); usersalary(user. delete(){usermapper.delete(3);}@testpublic void findbyid(){user user = usermapper.findbyid(1); system.out.println(user);}@testpublic void findall(){){){){){list <ユーザー>ユーザー= usermapper.findall上記は、編集者が紹介したMyBatis(簡潔で簡単な分析と理解しやすい)の簡単な紹介です。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!