Spring起動時のSpringデータMongoDBの例
この記事では、Gradleビルドツールを使用してSpringブート+ SpringデータMongoDBアプリケーションを作成する方法を説明します。
-
春のブート1.5.1.RELEASE
-
MongoDB
-
受け台
-
Java 8
1.プロジェクトの構成
標準的なプロジェクト構造。
プロジェクトの依存関係
2.1 Gradleビルドファイル。
build.gradle
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' jar { baseName = 'spring-data-mongodb-example' version = '1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile 'org.springframework.boot:spring-boot-starter-data-mongodb' }
2.2
spring-boot-startter-data-mongodb
を宣言し、数多くのライブラリを取得し、以下の依存関係を見直します:
コンソール
$ gradle dependencies --configuration runtime :dependencies ------------------------------------------------------------ ルートプロジェクト -------------------------------------------------- ---------- runtime - ソースセット 'main'のランタイムクラスパス。 \ --- org.springframework.boot:spring-boot-startter-data-mongodb: - > 1.5.1.RELEASE + --- org.springframework.boot:spring-boot-starter:1.5.1.RELEASE | + --- org.springframework.boot:spring-boot:1.5.1.RELEASE | | + --- org.springframework:spring-core:4.3.6.RELEASE | | \ --- org.springframework:スプリングコンテキスト:4.3.6.RELEASE | | + --- org.springframework:spring-aop:4.3.6.RELEASE | | | + --- org.springframework:spring-beans:4.3.6.RELEASE | | | | \ --- org.springframework:spring-core:4.3.6.RELEASE | | | \ --- org.springframework:spring-core:4.3.6.RELEASE | | + --- org.springframework:spring-beans:4.3.6.RELEASE(** ) | | + --- org.springframework:spring-core:4.3.6.RELEASE | | \ --- org.springframework:スプリング式:4.3.6.RELEASE | | \ --- org.springframework:spring-core:4.3.6.RELEASE | + --- org.springframework.boot:spring-boot-autoconfigure:1.5.1.RELEASE | | \ --- org.springframework.boot:spring-boot:1.5.1.RELEASE(** ) | + --- org.springframework.boot:spring-boot-starter-logging:1.5.1.RELEASE | | + --- ch.qos.logback:logback-classic:1.1.9 | | | + --- ch.qos.logback:logback-core:1.1.9 | | | \ --- org.slf4j:slf4j-api:1.7.22 | | + --- org.slf4j:jcl-over-slf4j:1.7.22 | | | \ --- org.slf4j:slf4j-api:1.7.22 | | + --- org.slf4j:jul-to-slf4j:1.7.22 | | | \ --- org.slf4j:slf4j-api:1.7.22 | | \ --- org.slf4j:log4j-over-slf4j:1.7.22 | | \ --- org.slf4j:slf4j-api:1.7.22 | + --- org.springframework:spring-core:4.3.6.RELEASE | \ --- org.yaml:snakeyaml:1.17 + --- org.mongodb:mongodb-driver:3.4.1 | + --- org.mongodb:mongodb-driver-core:3.4.1 | | \ --- org.mongodb:bson:3.4.1 | \ --- org.mongodb:bson:3.4.1 \ --- org.springframework.data:spring-data-mongodb:1.10.0.RELEASE + --- org.springframework:spring-tx:4.3.6.RELEASE | + --- org.springframework:spring-beans:4.3.6.RELEASE(** ) | \ --- org.springframework:spring-core:4.3.6.RELEASE + --- org.springframework:スプリングコンテキスト:4.3.6.RELEASE(** ) + --- org.springframework:spring-beans:4.3.6.RELEASE(** ) + --- org.springframework:spring-core:4.3.6.RELEASE + --- org.springframework:スプリング式:4.3.6.RELEASE(** ) + --- org.springframework.data:spring-data-commons:1.13.0.RELEASE | + --- org.springframework:spring-core:4.3.6.RELEASE | + --- org.springframework:spring-beans:4.3.6.RELEASE(** ) | + --- org.slf4j:slf4j-api:1.7.22 | \ --- org.slf4j:jcl-over-slf4j:1.7.22(** ) + --- org.slf4j:slf4j-api:1.7.22 \ --- org.slf4j:jcl-over-slf4j:1.7.22(** )
3. MongoDBの設定
application.properties
#mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=app1 #logging logging.level.org.springframework.data=debug logging.level.=error
4.春データ – MongoRepository
4.1 Springデータアノテーションを持つシンプルなモデル。
Domain.java
package com.mkyong.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "domain") public class Domain { @Id private long id; @Indexed(unique = true) private String domain; private boolean displayAds; //getters and setters }
4.2 `MongoRepository`を拡張すると、あなたは自動的にCRUD機能を持っています。
春のデータには多くの魔法のfindByクエリがあります。公式のhttp://docs.spring.io/spring-data/data-document/docs/current/reference/html/#mongodb.repositories.queries[Spring data MongoDB – クエリ方法]を参照してください。
DomainRepository.java
package com.mkyong.domain; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.util.List; //No need implementation, just one interface, and you have CRUD, thanks Spring Data public interface DomainRepository extends MongoRepository<Domain, Long> { Domain findFirstByDomain(String domain); Domain findByDomainAndDisplayAds(String domain, boolean displayAds); //Supports native JSON query string @Query("{domain:'?0'}") Domain findCustomByDomain(String domain); @Query("{domain: { $regex: ?0 } })") List<Domain> findCustomByRegExDomain(String domain); }
4.3
DomainRepository`のカスタムメソッドを作成するには、別のファイルに実装を作成し、
DomainRepository`がそれを拡張するようにする必要があります。
次の例では、 `MongoRepository`にカスタムの ‘特定のフィールドを更新する’メソッドを追加します。
4.3.1カスタムインターフェイス
DomainRepositoryCustom.java
package com.mkyong.domain; public interface DomainRepositoryCustom { int updateDomain(String domain, boolean displayAds); }
4.3.2実装クラス名は非常に厳密で、名前は “” CoreRepositoryInterface “Impl”でなければなりません。http://docs.spring.io/spring-data/data-document/docs/current/reference/html/を読んでください。 #repositories.custom-implementedations[SpringデータMongoDBカスタム実装]
DomainRepositoryCustom.java
package com.mkyong.domain; import com.mongodb.WriteResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; //Impl postfix of the name on it compared to the core repository interface public class DomainRepositoryImpl implements DomainRepositoryCustom { @Autowired MongoTemplate mongoTemplate; @Override public int updateDomain(String domain, boolean displayAds) { Query query = new Query(Criteria.where("domain").is(domain)); Update update = new Update(); update.set("displayAds", displayAds); WriteResult result = mongoTemplate.updateFirst(query, update, Domain.class); if(result!=null) return result.getN(); else return 0; } }
4.3.3
DomainRepository`は、カスタムインターフェース
DomainRepositoryCustom`を拡張します。
DomainRepository.java
package com.mkyong.domain; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.util.List; public interface DomainRepository extends MongoRepository<Domain, Long>, DomainRepositoryCustom { //other methods }
5.実行
5.1 Springブートアプリケーション。
Application.java
package com.mkyong; import com.mkyong.domain.Domain; import com.mkyong.domain.DomainRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Application { public static void main(String[]args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(DomainRepository domainRepository) { return args -> { Domain obj = domainRepository.findOne(7L); System.out.println(obj); Domain obj2 = domainRepository.findFirstByDomain("mkyong.com"); System.out.println(obj2); int n = domainRepository.updateDomain("mkyong.com", true); System.out.println("Number of records updated : " + n); }; } }
5.2 Gradleをビルドして実行します。
ターミナル
$ gradle build $ java -jar build/libs/spring-data-mongodb-example-1.0.jar . ________ __ ____ __ __ /\\/______'__ ____ __ __(__)__ ____ ____ __ \ \ \ \ ( ( )\______ | '__ | '__| | '__ \/__` | \ \ \ \ \\/ ______)| |__)| | | | | || (__| | ) ) ) ) ' |________| .____|__| |__|__| |__\____, |//// =========|__|==============|______/=/__/__/__/ :: Spring Boot :: (v1.5.1.RELEASE) //blah blah blah
6.よくある質問
6.1カスタム
MongoTemple`を作る方法は? A:デフォルトの設定を上書きするために、新しい `MongoTemplate
beanを宣言します。以下の例では、
__class`フィールドを削除するカスタム
MongoTemplate`を作成します。
Application.java
package com.mkyong; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; @SpringBootApplication public class Application { public static void main(String[]args) { SpringApplication.run(Application.class, args); } //remove __class @Bean public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory, MongoMappingContext context) { MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter); return mongoTemplate; } }
ソースコードをダウンロードする
ダウンロード:
spring-boot-data-mongodb-example.zip
(7 KB)
参考文献
データMongoDB – リファレンスドキュメント]。
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html
[Working
NoSQLテクノロジーを使用]。
http://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-gradle-plugin.html
[Spring
Boot Gradle Plugin]。
アプリケーションのビルド
春のブート]。リンク://gradle/gradle-display-project-dependency/[Gradle – 表示
プロジェクトの依存関係]