以前のレコードには、Springを使用せずに、JavaコードのMongoDBデータベースを直接接続および操作する記事があります。ここでは、Springを使用すると、JavaでMongodbの単純な操作を使用することを記録します。
Mavenパッケージの構成:
SpringとSpringMVCが含まれるため、関連するパッケージをインポートする必要もあります。
<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> spring_mongo </groupid> <artifactid> spring_mongo </artifactid> <パッケージ> war </packaging webApp </name> <url> http://maven.apache.org </url> <dependencies> <dependency> <groupid> org.springframework.data </groupid> <artifactid> spring-data-mongodb </artifactid> <バージョン> <GroupId> org.mongodb </groupid> <artifactid> mongo-java-driver </artifactid> <version> 3.0.3 </version> </dependency> <shiplency> computons-logging </groupid> <artifactid> commons-logging </artifactid> <bervers> </</</</</</</< <groupid> org.springframework </groupid> <artifactid> spring-test </artifactid> <version> 4.1.6.release </version> </dependency> <dependency> groupid> <artifactid> junit> junit </artifactid> <バージョン> <groupid> org.springframework </groupid> <artifactid> spring-context </artifactid> <version> 4.1.7.release </version> </dependency> <dependency> org.springframework </groupId> <artifactid> spring-context-support </artifactid> </> </> </> </dependency> <burtion> <plugins> <plugin> <artifactid> maven-compiler-plugin </artifactid> <version> 2.3.2 </version> <configuration> <source> 1.7 </source> <target> 1.7 </ターゲット> <エンコーディング> utf-8 </encoding> <bootclasspath> $ {java.home} /lib/rt.jar; $ {java.home} /lib/jce.jar </bootclasspath> </compilerararguments> </configuration> </plugin> </plugins> <finalName> spring_mongo </finalName> <スプリングの基本構成:
主に、注釈スキャンなどを有効にすることです。
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns:task = "http://www.springframework.org/schema/task" 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 = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd "> <! - 自動スキャン(自動インジェクション) - > <コンテキスト:component-scanベースパッケージ=" spring_mogo.dao.daoimp "/> <! /> <! - アノテーションをオンにします - > <コンテキスト:annotation-config /> < /beans>
SpringはMongodbを接続し、関連する工場の構成を確立します。
<?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:p = "http://www.springframework.org/schema/p" xmlns:mongo = "http://www.springframework.org/schema/data/mongo" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/schema/schema http://www.springframework.org/schema/data/mongo/spring-mongo.xsd "> <! - mongodbデータベースに接続するためのスプリング構成 - > <mongo:mongo-client host =" 192.168.0.0.201 "Port =" 27017 "" 27017 "資格情報= "Tuzongxun:123456@mongotest" id = "mongo"> <mongo:client-options write-concern = "safe"/> </mongo:mongo client> <mongo:db-factory id = "mongodbbactory" dbname = "mongotest" mongoref =対応する方法 - > <bean id = "mongotemplate"> <constructor-arg name = "mongodbfactory" ref = "mongodbfactory"/> </bean> </bean>
データベースに対応するエンティティクラス:
シリアル化インターフェイスを実装し、UID属性を設定する必要があることに注意してください。そうしないと、操作中にデータベースの返信結果をオブジェクト属性に直接変換することはできません。
パッケージspring_mongo.models; java.io.serializableをインポートします。パブリッククラスのusermodelはシリアル化可能{private static final long serialversionuid = 1l;プライベート文字列ユーザー名;プライベート文字列パスワード。 public usermodel(string username、string password){super(); this.username = username; this.password = password; } public string getUsername(){return username; } public void setUsername(string username){this.username = username; } public string getPassWord(){パスワードを返します。 } public void setPassword(string password){this.password = password; }} Spring構成に応じてMongoDBを動作させるmongotempleteを取得し、ApplicationContextAwareインターフェイスを実装する必要があります。
パッケージspring_mogo.dao.daoimp; Import org.springframework.beans.beansexception; org.springframework.context.applicationcontextをインポートします。 org.springframework.context.applicationcontextawareをインポートします。 Import org.springframework.data.mongodb.core.mongotemplate;パブリックアブストラクトクラスAbstractBaseMongotempleteは、ApplicationContextAware {Protected Mongotemplate Mongotemplate; / ** * @description Mongotemplate set onmongotemplate fill file * @param mongotemplate */ public void setMongotemplate(mongotemplate mongotemplate){this.mongotemplate = mongotemplate; } @Override public void setApplicationContext(applicationContext ApplicationContext)throws beansexception {mongotemplate mongotemplate = applicationContext.getBean( "mongotemplate"、mongotemplate.class); setMongoTemplate(mongotemplate); }}データベースと対応する実装クラスを操作するインターフェイス:
最も基本的な追加、削除、変更、および検索が実証されています。注意すべきは、返されたデータを受信したときのパラメーターの宣言とエンティティクラスの変換です。
(1)インターフェイス:
パッケージspring_mogo.dao; java.util.listをインポートします。 spring_mongo.models.usermodelをインポートします。 public interface userdao { / ** * query data * * @author:tuzongun * @title:findall * @param @return * @return list <usermodel> * @date 5月13日3:07:39 pm * @trows * / public list <usermodel> findall(); / ** *新しいデータ * * @author:tuzongxun * @title:insertuser * @param @param user * @return void * @date 2016年5月13日3:09:45 PM * @throws */ public void insertuser(usermodel user); / ** *データの削除 * * @Author:tuzongxun * @title:removeuser * @param @param username * @return void * @date 2016年5月13日3:09:55 PM * @throws */ public void removeuser(string username); / ** *データの変更 * * @author:tuzongxun * @title:updetuser * @param @param user * @return void * @date 2016年5月13日3:10:06 PM * @throws */ public void updetwususer(usermodel user); / **条件によるクエリ * * @author:tuzongxun * @title:findforrequery * @param * @return void * @date 2016年5月13日3:23:37 PM * @throws */ public List <Usermodel> FindForRequery(String Username); } (2)実装クラス、ここでは、さまざまな操作のためにmongotempleteを取得するために、abstractbasemongotempleteクラスを継承する必要があります。
パッケージspring_mogo.dao.daoimp; java.util.listをインポートします。 Import org.springframework.data.mongodb.core.query.criteria; org.springframework.data.mongodb.core.query.queryをインポートします。 org.springframework.data.mongodb.core.query.update; org.springframework.stereotype.componentをインポートします。 spring_mogo.dao.userdaoをインポートします。 spring_mongo.models.usermodelをインポートします。 com.mongodb.basicdbobjectをインポートします。 com.mongodb.dbobjectをインポートします。 @component( "userdaoimp")パブリッククラスuserdaoimp拡張abstractbasemongotemplete emplesments userdao { / ** * query all data * * @author:tuzongun * @title:findall * @description:todo * @param @return * @date 5月findall(){//対応するコーポスクラスと対応するコレクション名をコレクションのコレクション名を設定する必要があります。クエリ結果は直接マッピングされたリスト<usermodel> userlist = mongotemplate.findall(usermodel.class、 "user"); return userlist; } / ** *新しいデータ * * @author:tuzongxun * @title:insertuser * @description:todo * @param @param user * @date 2016年5月13日3:10:45 PM * @throws * / @Override public void insertasuser(usermodel user){//ドキュメントオブジェクトを設定します。 basicdbobject(); object.put( "username"、user.getusername()); object.put( "password"、user.getPassWord()); mongotemplate.insert(object、 "user"); } / ** *条件に応じてデータを削除 * * @author:tuzongxun * @title:removeuser * @description:todo * @param @param username * @date 2016年5月13日3:11:01 PM基準基準=新しい基準( "username"); Criteria.is(username); query.addcriteria(基準); mongotemplate.remove(query、 "user"); } / ** *データの変更 * * @author:tuzongxun * @title:updectuser * @description:dodo * @param @param user * @date 2016年5月13日3:11:12 PM * @throws * / @Override public void updetweduser(usermodel user){//基準基準=新しい基準( "username"); Criteria.is(user.getusername()); query.addcriteria(基準); //変更コンテンツアップデートupdate = update.update( "password"、user.getPassword()); //パラメーター:クエリ条件、結果の変更、コレクション名mongotemplate.updateFirst(query、update、 "user"); } / ** *条件に基づくクエリ * * @author:tuzongxun * @title:findforrequery * @description:todo * @param username * @date 5月13日4:08:15基準基準=新しい基準( "username"); Criteria.is(username); query.addcriteria(基準); //クエリ条件、セットに対応するエンティティクラス、セット名<usermodel> userlist = mongotemplate.find(query、usermodel.class、 "user"); return userlist; }}テストクラス:
上記のコードと構成の正しさを確認するために、テストクラスコードは次のとおりです。
パッケージspring_mongo.test; java.util.listをインポートします。 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.junit4.springjunit4classrunner; spring_mogo.dao.userdaoをインポートします。 spring_mongo.models.usermodelをインポートします。 @runwith(springjunit4classrunner.class)@contextconfiguration(locations = {"classpath:spring.xml"})public class mongotest {@autowired private userdao userdao; / ** *クエリテスト * * @author:tuzongxun * @title:monfindtest * @param * @return void * @date 2016年5月13日3:27:51 PM * @throws */ @test public void monfindtest(){list <usermodel> usermodels = userdao.findall(); if(usermodels!= null && usermodels.size()> 0){for(usermodel user:usermodels){system.out.println(user.getusername() + ":" + user.getpassword()); }}} / ** *データテストを挿入 * * @author:tuzongxun * @title:moninserttest * @param * @return void * @date 2016年5月13日3:27:38 PM * / @test public void moninserttest(){usermodel = new usermodel "; userdao.insertuser(user); this.monfindtest(); } / ** *削除テスト * * @author:tuzongxun * @title:monremovetest * @param * @return void * @date 2016年5月13日3:28:06 PM * @throws * / @test public void monremovetest(){string username = "test111"; userdao.removeuser(username); this.monfindtest(); } / ** *テスト修正 * * @author:tuzongxun * @title:monupdatetest * @param * @return void * @date 2016年5月13日3:50:08 PM * @throws * / @test public void monupdatest(){usermodel user = new usermodel(test111 ""); userdao.updateuser(user); this.monfindtest(); } / ** *条件によるクエリ * * @author:tuzongxun * @title:monfindforruq * @return void * @date 2016年5月13日4:10:53 PM * @throws * / @test public void void monfindforruq(){string username = "test111";リスト<Usermodel> usermodels = userdao.findforrequery(username); if(usermodels!= null && usermodels.size()> 0){for(usermodel user:usermodels){system.out.println(user.getusername() + ":" + user.getpassword()); }}}}後期段階でデモをダウンロードします:デモ
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。