1.開発環境を構築します
1.1。 Mavenを使用してWebプロジェクトを作成します
次のコマンドを実行します。
コードを次のようにコピーします。MVNARCHETYPE:CREATE -DGROUPID = ME.GACL -DARTIFACTID = SPRING4 -MYBATIS3 -DARCHETYPEARTID = MAVEN -ARCHETYPE -WEBAPP -DINTERACTIVEMODE = fals
下の図に示すように:
作成されたプロジェクトは次のとおりです。
pom.xmlファイルを編集します
<プロジェクトXMLNS = "http://maven.apache.org/pom/ .." xmlns:xsi = "http://www.w.org//xmlschema-instance" xsi:schemalocation = "http://maven.apach.org/pom/ .. http://maven.apache.org/maven-v__.xsd "> <modelversion> .. </modelversion> <groupid> me.gacl </groupid> <artifactid> spring-mybatis </artifactid> <パッケージ> war </packaging> <バージョン> <url> http://maven.apache.org </url> <dependencies> <依存関係> groupid> junit </groupid> <artifactid> </artifactid> <バージョン> </バージョン> <scope> test </scope> </despendency> </dependencies> </bultsmamame> </burtion
<name> spring4-mybatis3 maven webapp </name>セクションを変更し、「maven webapp」のスペースを含むコンテンツを削除します。それ以外の場合、Mavenがプロジェクトをコンパイルすると、スペースが原因で不可解なエラーが発生し、 <name> spring4-mybatis3 </name>に変更されます。
また、以下を削除します。
<Dependency> GroupId> junit </groupId> <artifactid> junit </artifactid> <version> .. </version> <scope> test </scope> </dependency>
この部分は、JUNITのJARパッケージ依存関係情報です。このバージョンは低すぎます。このJunitテストバージョンは使用していません。変更されたpom.xmlコンテンツは次のとおりです。
<プロジェクトXMLNS = "http://maven.apache.org/pom/ .." xmlns:xsi = "http://www.w.org//xmlschema-instance" xsi:schemalocation = "http://maven.apach.org/pom/ .. http://maven.apache.org/maven-v__.xsd "> <modelversion> .. </modelversion> <groupid> me.gacl </groupid> <artifactid> spring-mybatis </artifactid> <パッケージ> war </packaging> <バージョン> - snapshot </version </version < <url> http://maven.apache.org </url> <dependencies> </dependencies> <burtion> <finalName> spring-mybatis </finalName> </build> </project>
1.2。作成されたプロジェクトをmyeclipseにインポートします
特定の操作手順を以下の図に示します。
下の図に示すように、[SRC/Main/Java]、[SRC/Test/Resources]、および[SRC/TEST/JAVA]、[SRC/Main/Java]、[SRC/TEST/RESOUCES]、および[SRC/TEST/JAVA]の3つのソースフォルダーを手動で作成します。
この時点で、すべてのプロジェクト建設作業が完了しました。
2。データベースとテーブルを作成します(mysql用)
SQLスクリプトは次のとおりです。
データベースSpring4_mybatis3を作成します。Spring4_mybatis3を使用します。テーブルをドロップします。
作成されたデータベースとテーブルは次のとおりです。
3.ジェネレーターツールを使用してコードを生成します
Entityクラス、SQLマッピングファイル、および作成されたデータベーステーブルに基づいてMyBatisテーブルに対応するDAOを生成できるジェネレーターツールを見つけ、Generator.xmlファイルをGeneratorツールのルートディレクトリに見つけます。このファイルは、下の図に示すように、コード生成ルールの構成に使用されます。
Generator.xmlファイルを編集します。コンテンツは次のとおりです。
<?xmlバージョン= "。" encoding = "utf - "?> <!doctype generatorconfiguration public " - // mybatis.org//dtd mybatisジェネレーター構成。場所= "e:/repository/mysql/mysql-connector-java /../ mysql-connector-java -... jar"/> <! - <classpathentry location = "c:/oracle/product /../ db_/jdbc/lib/ojdbc.jar <CommentGenerator> <Property Name = "SupplessallComments" value = "true"/> </commentGenerator> <! - データベースリンクURL、ユーザー名、パスワード - > <jdbcconection driverclass = "com.mysql.jdbc.driver" connectnurl = "jdbcパスワード= "xdp"> <! - <jdbcconnection driverclass = "oracle.jdbc.driver.oracledriver" connectionurl = "jdbc:oracle:thin:@localhost :: orcl" userid = "msa" password = "msa"> - > </jdbccnection /> < /javatyperesolver> <! - エンティティクラスのパッケージ名と場所を生成します。ここで、生成されたエンティティクラスはパッケージの下に配置されます。gacl.domain-> <javamodelgenerator targetpackage = "me.gacl.domain" targetproject = "c:/gacl/spring-mybatis/src/main/java"> <プロパティnam </javamodelgenerator> <! - 生成されたSQLマップファイルパッケージ名と場所。ここで、生成されたsqlマップファイルをパッケージの下に配置します。gacl.mapping-> <sqlmapgenerator targetpackage = "me.gacl.mapping" c:/users/gacl/spring-mybatis/src/main/java "> <プロパティ名=" gumppage " DAOのパッケージ名と場所。ここで、生成されたdaoクラスをパッケージの下に配置します。gacl.dao-> <javaclientgenerator type = "xmlmapper" targetpackage = "me.gacl.dao"ターゲットプロジェクト= " < /javaclientGenerator> <! - それらのテーブルを生成する(TableNameおよびdomainobjectNameを変更) - > <table tableName = "t_user" domainobjectname = "user" enablecountbyexample = "false" enableUpdateByexample = "enableteletebyexample =" false false </context> </generatorConfiguration>
コマンドラインウィンドウを開き、ジェネレーターツールのルートディレクトリに切り替えて、次のコマンドを実行します。
Java -Jar MyBatis -Generator -Core -1.3.2.Jar -Configfile Generator.xml -Overwrite
下の図に示すように:
ちょうど今、Generator.xmlファイルに生成されたコードとSQLマッピングファイルを設定して、生成されたコードとSQLマッピングファイルをディレクトリ「C:/GACL/SPRING4-MYBATIS3/SRC/MAIN/JAVA」に配置しました。このディレクトリは、Spring4-Mybatis3プロジェクトがあるディレクトリです。 SRC/Main/Javaディレクトリを更新すると、下の図に示すように、生成されたコードとマッピングファイルが表示されます。
生成されたコードとマッピングファイルを1行に変更する必要はなく、プロジェクトに直接適用できます。ジェネレーターツールによって生成されたコードとマッピングファイルを見てみましょう。
1。生成されたDAOクラス
me.gacl.daoをパッケージ化します。 me.gacl.domain.userをインポートします。パブリックインターフェイスusermapper {int deletebyprimarykey(string userid); int insert(ユーザーレコード); int insertSelective(ユーザーレコード);ユーザーSelectByPrimaryKey(String UserID); int updateByPrimaryKey(ユーザーレコード); }生成されたUserMapperは、T_USERテーブルを追加、削除、変更、検索する方法を定義するインターフェイスです。
2。生成されたエンティティクラス
me.gacl.domainをパッケージ化します。 Import Java.util.date;パブリッククラスユーザー{private string userid;プライベート文字列ユーザー名; Private Date userbirthday;プライベートダブルユーザーサラリー。 public string getUserid(){return userid; } public void setuserid(string userid){this.userid = userid == null? null:userid.trim(); } public string getUsername(){return username; } public void setusername(string username){this.username = username == null? null:username.trim(); } public date getuserbirthday(){return userbirthday; } public void setuserbirthday(date userbirthday){this.userbirthday = userbirthday; } public double getUserSarary(){return usersalary; } public void setusersalary(double usersalary){this.usersalary = usersalary; }}ユーザークラスは、T_USERテーブルの対応するエンティティクラスです。ユーザークラスで定義されている属性は、T_USERテーブルのフィールドに1つずつ対応しています。
3。生成されたSQLマッピングファイル
<?xmlバージョン= "。" encoding = "UTF-"? type = "me.gacl.domain.user"> <id column = "user_id" property = "userid" jdbctype = "char" /> <result column = "user_name" property = "username" jdbctype = "varchar" /> <result column = "user_birthday" "userbirthday =" userbirthday "> <" userbirthday = "userbirthday =" userbirthday "プロパティ= "usersalary" jdbctype = "double"/> </resultmap> <sql id = "base_column_list"> user_id、user_name、user_birthday、user_salary </sql> <select id = "selectbyprimarykey" resultmap = "baseresultmap" parametertype " refid = "base_column_list"/> from t_user where user_id =#{userid、jdbctype = char} </select> <delete id = "deletebyprimarykey" parametertype = "java.lang.String"> delete from t_user where user_id =#{intectece> <intectece parametertype = "me.gacl.domain.user"> t_user(user_name、user_birthday、user_salary)値(#{userid、jdbctype = char}、#{username、jdbctype = varchar}、 #{usersalary、jdbctype = double})</insert> <挿入id = "insertselective" parametertype = "me.gacl.domain.user"> t_user <triam freix = "(" fungix = ")" suffixoverrides = "、"、 "> <if suffixoverrides =") user_name、</if> <test = "userbirthday!= null"> user_birthday、</if> <if test = "usersalary!= null"> user_salary、</if> </trix = "values(" suffix = ")" suffixoverrides = "、" null! #{userId、jdbctype = char}、</if> <if> <if> "username!= null">#{jdbctype = varchar}、</if> <"userbirthday!= null">#{userbirthday、jdbctype}、null " #{usersalary、jdbctype = double}、</if> </trim> </insert> <update id = "updatebyprimarykeyselective" parametertype = "me.gacl.domain.user">更新t_user <set> <if test = "username!= null" test = "userbirthday!= null"> user_birthday =#{userbirthday、jdbctype = date}、</if> <if> <"usersalary!= null"> usersalary、usersalary、jdbctype = double}、</set = </set> </set> id = "updatebyprimarykey" parametertype = "me.gacl.domain.user"> update t_user set user_name =#{username、jdbctype = varchar}、#{userbirthday、jdbctype = date}、userarary = {userarary、jdbctypeの場合、ユーザー、jdbctype #{userid、jdbctype = char} </update> </mapper>usermapper.xmlファイルのコンテンツは、T_USERテーブルを操作するSQLステートメントを記述します。 usermapper.xml構成で注意を払う必要があるいくつかの小さな詳細に焦点を当てましょう。
1。Usermapper.xmlの<mapper>タグの名前空間は、usermapperインターフェイスの完全なクラス名でなければなりません。
2。USERMAPPER.XML定義操作データベースのID属性の値は、以下の図に示すように、UserMapperインターフェイスで定義されたメソッド名と一致する必要があります。
上記の2つの要件の理由は、MyBatisがUserMapperインターフェイスとUserMapper.xmlファイルに基づいてUsermapperインターフェイスで定義された関連するメソッドを自動的に実装できるため、UserMapperインターフェイスの特定の実装コードを記述する必要がなくなりました。
4。スプリングとマイバティスの統合
まず、プロジェクトに必要な関連するJARパッケージを追加する必要があります。次の図に示すように、Mavenの中央リポジトリ:http://search.maven.org/にアクセスして、必要な関連するJARパッケージを見つけることができます。
検索ボックスに探しているJARパッケージの名前を入力し、[検索]ボタンをクリックして、探しているJARパッケージを見つける必要があります。
4.1。スプリングとマイバティス関連のJARパッケージを追加します
1.スプリングコアを追加し、下の図に示すように、スプリングコアキーワードを検索して検索します。
次の図に示すように、スプリングコアに関する依存関係の説明情報を見つけます。
意思
<Dependency> groupId> org.springframework </groupid> <artifactid> spring-core </artifactid> <version> 4.1.4.Release </version> </dependency>
次のように、プロジェクトのpom.xmlファイルにコピーします。
<Project XMLNS = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation = "http://maven.apach/4.0. http://maven.apache.org/maven-v4_0_0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> me.gacl </groupid> <artifactid> spring4-mybatis3 </artifactid> <パッケージ> war <name> spring4-mybatis3 </name> <url> http://maven.apache.org </url> <dependencies> <! - spring4.1.4コアパッケージ - > <依存関係> <groupid> org.springframework </groupid> <artifactid> spring </artifactId> </dependencies> <build> <finalName> spring4-mybatis3 </finalName> </build> </project>
このようにして、Mavenは、Mavenの中央リポジトリからローカルリポジトリにスプリングコアJARパッケージを自動的にダウンロードし、以下に示すようにスプリングコアJARパッケージとその関連依存関係をプロジェクトに追加するのに役立ちます。
Spring4.xおよびMyBatis3.xで必要な関連JARパッケージは、上記の方法で検索してからプロジェクトに追加できます。 spring4.xとmybatis3.xに関連する関連JARパッケージを追加した後、pom.xmlファイルのコンテンツは次のとおりです。
<プロジェクトXMLNS = "http://maven.apache.org/pom/ .." xmlns:xsi = "http://www.w.org//xmlschema-instance" xsi:schemalocation = "http://maven.apach.org/pom/ .. http://maven.apache.org/maven-v__.xsd "> <modelversion> .. </modelversion> <groupid> me.gacl </groupid> <artifactid> spring-mybatis </artifactid> <パッケージ> war </packaging> <バージョン> - snapshot </version </version < <url> http://maven.apache.org </url> <dependencies> <! - スプリングコアパッケージを追加 - > <依存科学> <groupid> org.springframework </groupid> <artifactid> spring-core </artifactid> <バージョン> </バージョン> < <groupid> org.springframework </groupid> <artifactid> spring-context </artifactid> <version> ...リリース</version> </dependency> <! - spring-txパッケージ - > <依存関係> <groupid> org.springframework </groupid> <artifactid> spring> </</</</</</</</</</</</</</</</</</</バージョンspring-jdbcパッケージ - > <依存関係> <groupid> org.springframework </groupid> <artifactid> spring-jdbc </artifactid> <bersion> ...リリース</version> </dependency> <! - spring-jdbcパッケージ - 追加<バージョン> ...リリース</version> </dependency> <! - ユニットテストを容易にするには、スプリングテストパッケージを追加します - > <依存関係> <groupid> org.springframework </groupid> <artifactid> springtest </artifactid> <バージョン... <artifactid> spring-web </artifactid> <version> ...リリース</version> </dependency> <! - aspectjweaverパッケージを追加 - > <依存関係> <groupid> aspectj </groupid> <artifactid> aspectjweaver </artifactid> <バージョン> .. </バージョン> <groupid> org.mybatis </groupid> <artifactid> mybatis </artifactid> <version> .. </version> </dependency> <! - springと統合されたmybatisコアパッケージを追加 - > <依存関係> <groupid> org.mybatis </groupid> <artifactid> <! - servlet.coreパッケージを追加 - > <依存関係> <groupid> javax.servlet </groupid> <artifactid> javax.servlet-api </artifactid> <バージョン> .. </version> </dependency> <dependency> <groupid> javax.servlet.jsp < <バージョン> ..- b </version> </dependency> <! - jstl-> <dependency> <groupid> javax.servlet </groupid> <artifactid> jstl </artifactid> <バージョン> </dependency> < <artifactid> mysql-connector-java </artifactid> <version> .. </version> </dependency> <! - druid接続プールパッケージの追加 - > <依存関係> com.alibaba> <artifactid> druid> druid </artifactid> <バージョン> .. <GroupId> junit </groupid> <artifactid> junit </artifactid> <version>。
4.2。関連する構成ファイルを記述します
1。DBCONFIG.PROPERTIES
src/main/resourcesディレクトリにdbconfig.propertiesファイルを作成して、mysqlデータベースへの接続に関する関連情報を記述します。 dbconfig.propertiesの内容は次のとおりです。
DriverClassName = com.mysql.jdbc.driverValidationQuery = select 1jdbc_url = jdbc:mysql:// localhost:3306/spring4_mybatis3?useunicode = true&charatereCoding = utf-8&zerodatetimebehavior = converttonulljdbc_username = rootjdbc_password = xdp
2。Spring.xml(Spring Frameworkの構成ファイル)
src/main/resourcesディレクトリにspring.xmlファイルを作成します。 spring.xmlファイルは、Springフレームワーク用に記述されたコア構成ファイルです。 spring.xmlの内容は次のとおりです。
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemalocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/sche ma/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context/spring-context-3.0.xsd "> <! - dbconfig.propertiesプロパティファイルを紹介 - > <コンテキスト:プロパティプレイスホルダー場所= "classpath:dbconfig.properties" /> <! - dbconfig.propertiesプロパティファイルを紹介します - > <コンテキスト:プロパティプレイスホルダー場所= "classpath:dbconfig.porperties" />>> <! @Serviceクラスの注釈で注釈が付けられたパッケージとすべてのクラス - > <コンテキスト:Component-ScanSycanベースパッケージ= "me.gacl.service" /> < /beans>
spring.xmlファイルの構成は非常に簡単で、構成は2つしかありません。
3。Spring-Mybatis.xml(SpringおよびMyBatisと統合された構成ファイル)
SRC/Main/ResourcesディレクトリにSpring-Mybatis.xmlファイルを作成します。 Spring-Mybatis.xmlファイルは、SpringフレームワークとMyBatisフレームワークの統合のために記述された構成ファイルです。 spring-mybatis.xmlの内容は次のとおりです。
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:tx = "http://www.springframework.org/schema/tx" xmlns:aop = "http://www.springframework.org/schema/aop" xsi:schemalocation = " http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework/ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean id = "dataSource"> <プロパティ名= "jndiname" value = "$ {jndiname}"> </property> </bean> - > <! - ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== name = "username" value = "$ {jdbc_username}" /> <property name = "password" value = "$ {jdbc_password}" /> <! - 接続サイズの初期化 - > <プロパティname = "Initialsize" value = "0" /> < free - > <プロパティ名= "maxidle" value = "20" /> <! - 接続の最小数無料 - > <プロパティ名= "minidle"値= "0" /> <! name = "maxpoolpreparedStatementperconnectionSize" value = "33" /> - > <プロパティ名= "validationquery" value = "$ {validationquery}" /> <プロパティ名= "testonborrow" value = "false" /> <プロパティname = "testonborrow" "value =" "false =" fallid ">" false " />" false " value = "true" /> <! - 検出インターバルを実行するのに時間がかかる時間を構成して、閉じる必要があるアイドル接続をMillisecondsで検出します - > <プロパティNAME = "TimeEvictionRunsmillis" value = "60000" /> <! value = "25200000" /> <! - removeabandoned function-> <プロパティ名= "removeabandoned" value = "true" /> <! - つまり、30分 - > <プロパティname = "removeabbandoned timeout" value = "1800" /> <! - 出力エラー= <データベース - > <! - <プロパティ名= "フィルター" value = "stat" /> - > <プロパティ名= "フィルター" value = "mergestat" /> < /bean> <! - ========================================================================================= ============================================================================================================================================ ============================================================================================================================================ ============================================================================================================================================ ================================================================================ ============================================================================== ============================================================================== ============================================================================== ============================================================================== ============================================================================== ============================================================================== ==============================================================================マニュアル構成値を保存= "classpath:me/gacl/mapping/*。xml" in Configuration.xmlは、usermapper.xmlのclasspath(classpath)の下のme.gacl.mappingパッケージのすべてのxmlファイルを指します。 value = "classpath:me/gacl/mapping/*。xml"/> </bean> <! - 構成スキャナー - > <bean> <! - me.gacl.daoパッケージとすべてのマッピングインターフェイスクラスをそのサブパッケージの下でスキャン - > <プロパティ名= "basepackage" "sqlname"/< value = "sqlsessionfactory" /> < /bean> <! - ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== ========================================================================== Transaction-Manager = "TransactionManager" /> - > <! - インターセプター構成 - > <TX:アドバイスID = "TransactionAdvice" Transaction-Manager = "TransactionManager"> <TX:属性> <TX:メソッドname = "add*" propagation = "" rebuly " />> <tx:method*" propagation = "methogation" /<tx " /<tx" propagation = "必須" /> <tx:メソッド名= "save*" propagation = "experagation" /> <tx:method name = "update*" propagation = "execrage" /> <tx:method name = "modify*" propagation = " /> <tx:method name =" edit*"propagation =" name = "remove*" propagation = "experagation" /> <tx:method name = "repain" propagation = "expect" /> <tx:method name = "delandrepair" propagation = "required" /> <tx:method name "delandrepair" delandrepair "delandrepair" delandrepagation = "neclowed" /> <tx:method name = " propagation = "supports" /> <tx:method name = "load*" propagation = "supports" /> <tx:method name = "search*" suppeats " /> <tx:method name =" datagrid*"propagation ="サポート " </tx:属性> </tx:アドバイス> <aop:config> <aop:pointcut id = "transactionpointcut" expression = "execution(*me.gacl.service ..*inft。*(..)"/> <aop:advisor pointcut-ref = "spitlcut-ref =" transactionpointcut "advize-ref ="/< jdbc - > <bean id = "druid-stat-interceptor"> </bean> <bean id = "druid-stat-point-cut" scope = "prototype"> <プロパティ名= "パターン"> <値> me.gacl.service。 Advieg-ref = "Druid-Stat-interceptor" PointCut-Ref = "Druid-Stat-PointCut"/> </aop:config> </beans>この時点で、以下の図に示すように、関連する構成ファイルが記述されています。
4.3。ユニットテストを実施します
上記の2つのステップの後、スプリング4とMyBatis3の統合が完了しました。次に行う必要があるタスクは、Spring4とMyBatis3の統合が成功したかどうかをテストするためにユニットテストを実施することです。
1. src/main/javaディレクトリにme.gacl.serviceパッケージを作成し、以下に示すように、me.gacl.serviceパッケージにuserserviceiインターフェイスを作成します。
me.gacl.serviceをパッケージ化します。 me.gacl.domain.userをインポートします。パブリックインターフェイスuserservicei { / ***ユーザー* @paramユーザー* / void adduser(user user); / ** *ユーザーIDに基づいてユーザーを取得 * @param userid * @return */ user getUserbyId(string userid); }2. src/main/javaディレクトリにme.gacl.service.implパッケージを作成し、me.gacl.service.implパッケージでuserserviceiインターフェイスの実装クラスを作成します。
me.gacl.service.implをパッケージ化します。 Import org.springframework.beans.factory.annotation.autowired; org.springframework.stereotype.serviceをインポートします。 me.gacl.dao.usermapperをインポートします。 me.gacl.domain.userをインポートします。 me.gacl.service.userserviceiをインポートします。 /** * @author gacl * @service annotationを使用してuserserviceimplクラスをサービスとして注釈を付けます *サービスIDはuserservice */@service( "userservice")パブリッククラスユーザーサービスを実装します{/** * @autowired nonotationを使用してユーザーマッピングを使用して、ユーザーユーザーを使用します。 @autowired private usermapper usermapper; // Inject dao @override public void adduser(user user){usermapper.insert(user); } @Override public user getUserbyId(string userid){return usermapper.semaptbyprimarykey(userid); }}作成された2つのクラスは次のとおりです。
3. SRC/test/javaディレクトリにユニットテストクラスを作成し、新しいme.gacl.testパッケージを作成してから、このパッケージの下でmybatistestクラスを作成します。コードは次のとおりです。
me.gacl.testをパッケージ化します。 Import Java.util.date; java.util.uuidをインポートします。 me.gacl.domain.userをインポートします。 me.gacl.service.userserviceiをインポートします。 // me.gacl.service.userserviceiをインポートします。 org.junit.beforeをインポートします。 Import org.junit.test; org.springframework.context.applicationcontextをインポートします。 import org.springframework.context.support.classpathxmlapplicationcontext;パブリッククラスmybatistest {private userservicei userservice; /** * This before method is executed before all test methods and is only executed once* All initialization work during Junit unit testing can be performed in this method* For example, initializing ApplicationContext and userService in the before method */ @Before public void before(){ //Create Spring context using the two configuration files "spring.xml" and "spring-mybatis.xml" ApplicationContext ac = new classPathXMLApplicationContext(new String [] {"Spring.xml"、 "Spring-mybatis.xml"}); // spring container userserservice =(userservicei)ac.getbean( "userservice")からBeanのIDに基づいて使用するユーザーサービスオブジェクトを取得します。 } @test public void testAdduser(){// ApplicationContext AC = new ClassPathXMLApplicationContext(new String [] {"Spring.xml"、 "Spring-mybatis.xml"}); // userservicei userservice =(userservicei)ac.getbean( "userservice"); user user = new user(); user.setuserid(uuid.randomuuid()。toString()。fallingeall( " - "、 "")); user.setUsername( "White Tiger God Emperer XDP"); user.setuserbirthday(new Date()); user.setUserarary(d); userservice.adduser(user); }}ユニットテストコードを実行すると、次のエラーが報告されます。
エラーメッセージは、プロジェクトのクラスをコンパイルするためにMavenを使用しなかったため、クラス「me.gacl.test.mybatistest」が見つかりませんでした。
次に、Mavenを使用してプロジェクトをコンパイルし、以下に示すように、プロジェクトのPOM.XMLファイル→【DEBUGを】→Mavenインストールとして選択します。
コンピレーションの結果は次のとおりです。
ここでは、Mavenインストールを実行した後に遭遇した問題についてお話します。 Maven Installコマンドを最初に実行したとき、次の乱雑なエラーを見ました。
その後、プロジェクトを削除し、プロジェクトを再輸入し、次の図に示すように、クリーンプロジェクト操作を実行しました。
Mavenインストール操作を実行した後、通常はコンパイルして渡すことができます。これにより、長い間落ち込んでいます。これが私のプロジェクト構成の理由ではなく、Mavenの理由であるはずです。なぜそうなのかわかりません。とにかく、これは解決策です。 Mavenインストール操作を正常にコンパイルできない状況に遭遇した場合:3つのステップを使用してみてください:Maven Clean→Clean Project→Mavenインストールを解決して問題を解決します。
定期的なJunitを使用したユニットテストに加えて、Springが提供するJunitテストフレームワークをユニットテストに使用し、ME.gacl.Testの下に新しいMyBatistESTESTBYSPRINGSPRINGTESTFRAMEWORKクラスを作成することもできます。コードは次のとおりです。
me.gacl.testをパッケージ化します。 Import Java.util.date; java.util.uuidをインポートします。 me.gacl.domain.userをインポートします。 me.gacl.service.userserviceiをインポートします。 Import org.junit.test; Import org.junit.runner.runwith; Import org.springframework.beans.factory.annotation.autowired; org.springframework.test.context.contextconfigurationをインポートします。 Import org.springframework.test.context.junit.springjunitclassrunner; @runwith(springjunitclassrunner.class)// @contextconfigurationアノテーションが設定され、アノテーションの場所属性がスプリングと構成ファイル@contextconfigurationで指定されている( "classpath:spring.xml"、 "spring-mybatis.xml") {// inject userservice @autowired private userservicei userservice; @test public void testadduser(){user user = new user(); user.setuserid(uuid.randomuuid()。toString()。fallingeall( " - "、 "")); user.setusername( "xdp_gacl_white tiger god emperer"); user.setuserbirthday(new Date()); user.setUserarary(d); userservice.adduser(user); } @test public void testgetuserbyid(){string userid = "fbcebfdada"; user user = userservice.getuserbyid(userid); system.out.println(user.getusername()); }}以下に示すように、これら2つのテスト方法を実行し、通常のテストに合格します。
この時点で、たとえフレームワークのすべての統合テストが渡されたとしても、統合は成功しました。
4.4。 Test in web server
1、编辑web.xml文件,添加spring监听器配置项,内容如下:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <description>Spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- ContextLoaderListener初始化Spring上下文时需要使用到的contextConfigLocation参数--> <context-param> <param-name>contextConfigLocation</param-name> <!-- 配置spring.xml和spring-mybatis.xml这两个配置文件的位置,固定写法--> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value> </context-param></web-app>
2、在UserMapper接口中添加一个获取所有用户信息的getAllUser()方法,如下所示:
package me.gacl.dao; import java.util.List; import me.gacl.domain.User; public interface UserMapper { int deleteByPrimaryKey(String userId); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(String userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); /**Get all user information* @return List<User> */ List<User> getAllUser(); }3、在UserMapper.xml文件中编写getAllUser()方法要执行的SQL语句,如下所示:
<?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="me.gacl.dao.UserMapper" > <resultMap id="BaseResultMap" type="me.gacl.domain.User" > <id column="user_id" property="userId" jdbcType="CHAR" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="user_birthday" property="userBirthday" jdbcType="DATE" /> <result column="user_salary" property="userSalary" jdbcType="DOUBLE" /> </resultMap> <sql id="Base_Column_List" > user_id, user_name, user_birthday, user_salary </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from t_user where user_id = #{userId,jdbcType=CHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String" > delete from t_user where user_id = #{userId,jdbcType=CHAR} </delete> <insert id="insert" parameterType="me.gacl.domain.User" > insert into t_user (user_id, user_name, user_birthday, user_salary) values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, #{userSalary,jdbcType=DOUBLE}) </insert> <insert id="insertSelective" parameterType="me.gacl.domain.User" > insert into t_user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="userId != null" > user_id, </if> <if test="userName != null" > user_name, </if> <if test="userBirthday != null" > user_birthday, </if> <if test="userSalary != null" > user_salary, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="userId != null" > #{userId,jdbcType=CHAR}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="userBirthday != null" > #{userBirthday,jdbcType=DATE}, </if> <if test="userSalary != null" > #{userSalary,jdbcType=DOUBLE}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="me.gacl.domain.User" > update t_user <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="userBirthday != null" > user_birthday = #{userBirthday,jdbcType=DATE}, </if> <if test="userSalary != null" > user_salary = #{userSalary,jdbcType=DOUBLE}, </if> </set> where user_id = #{userId,jdbcType=CHAR} </update> <update id="updateByPrimaryKey" parameterType="me.gacl.domain.User" > update t_user set user_name = #{userName,jdbcType=VARCHAR}, user_birthday = #{userBirthday,jdbcType=DATE}, user_salary = #{userSalary,jdbcType=DOUBLE} where user_id = #{userId,jdbcType=CHAR} </update> <!-- ==============以下内容是根据自身业务扩展的内容======================= --> <!-- select标签的id属性与UserMapper接口中定义的getAllUser方法要一模一样--> <select id="getAllUser" resultMap="BaseResultMap"> select user_id, user_name, user_birthday, user_salary from t_user </select></mapper>4、在UserServiceI接口中也添加一个getAllUser()方法,如下:
package me.gacl.service; import java.util.List; import me.gacl.domain.User; public interface UserServiceI { /** * Add user* @param user */ void addUser(User user); /** * Get user based on user id* @param userId * @return */ User getUserById(String userId); /** Get all user information* @return List<User> */ List<User> getAllUser(); }5、在UserServiceImpl类中实现getAllUser方法,如下:
package me.gacl.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import me.gacl.dao.UserMapper; import me.gacl.domain.User; import me.gacl.service.UserServiceI; /** * @author gacl * 使用@Service注解将UserServiceImpl类标注为一个service * service的id是userService */ @Service("userService") public class UserServiceImpl implements UserServiceI { /** * 使用@Autowired注解标注userMapper变量, * 当需要使用UserMapper时,Spring就会自动注入UserMapper */ @Autowired private UserMapper userMapper;//注入dao @Override public void addUser(User user) { userMapper.insert(user); } @Override public User getUserById(String userId) { return userMapper.selectByPrimaryKey(userId); } @Override public List<User> getAllUser() { return userMapper.getAllUser(); } }6、在src/main/java目录下创建一个me.gacl.web.controller包,然后在me.gacl.web.controller下创建一个UserServlet,如下:
package me.gacl.web.controller; java.io.ioexceptionをインポートします。 import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import me.gacl.domain.User; import me.gacl.service.UserServiceI; /** * @author gacl * @WebServlet is an annotation provided by Servlet. The purpose is to label a normal java class that inherits the HttpServlet class as a Servlet * After the UserServlet uses the @WebServlet annotation, there is no need to configure it in web.xml */ @WebServlet("/UserServlet") public class UserServlet extends HttpServlet { //UserService private UserServiceI userService; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get all user information List<User> lstUsers = userService.getAllUser(); request.setAttribute("lstUsers", lstUsers); request.getRequestDispatcher("/index.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } public void init() throws ServletException { //Get Spring context object when Servlet initialization (ApplicationContext) ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //Get userService from ApplicationContext userService = (UserServiceI) ac.getBean("userService"); } }7、编辑index.jsp页面,用于展示查询到的用户信息,内容如下:
<%@ page language="java" pageEncoding="UTF-8"%><%--引入JSTL核心标签库--%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE html><html> <head> <title>显示用户信息</title> <style type="text/css"> table,td{ border: 1px solid; border-collapse: collapse; } </style> </head> <body> <table> <tr> <td>用户ID</td> <td>用户名</td> <td>用户生日</td> <td>工资</td> </tr> <%--遍历lstUsers集合中的User对象--%> <c:forEach var="user" items="${lstUsers}"> <tr> <td>${user.userId}</td> <td>${user.userName}</td> <td>${user.userBirthday}</td> <td>${user.userSalary}</td> </tr> </c:forEach> </table> </body></html>8、执行maven install命令编译项目,然后将项目部署到tomcat服务器中运行,注意,由于要使用Servlet3.0,所以必须将项目部署到tomcat7.x以上的服务器中去运行,如下所示:
输入地址:http://localhost:8080/spring4-mybatis3/UserServlet访问UserServlet,访问结果如下:
可以看到,t_user表中的用户信息全部查询出来显示到页面上了。这样在web服务器中的测试也正常通过了。
以上就是Spring4.x与MyBatis3.x整合的全部内容了。编写这个整合例子花了不少时间,使用Maven编译时总是出现莫名其妙的问题,有时候成功,有时候失败,反正很莫名其妙。如果遇到执行Maven install操作不能正常编译通过的情况:可以尝试采用:Maven clean→Clean项目→Maven install这三个步骤去解决问题