SpringDataMongoDB basic instance code
1. Download the example from the official website below, and the download address is as follows: http://www.springsource.org/samples 2. Troubleshooting, the The SpringExample just downloaded has an error. First of all, it is not a maven project. Right-click to convert it into a maven project, and add some dependencies, such as spring-aop, spring-context, spring-core, log4j and other dependencies. At the same time, update your dependent packages and configurations. After the final operation is successful, run the next step. 3. Code explanation. 3.1 Method 1 (open mongo.exe in annotation mode, and create database yourdb and document yourCollection at the same time), the code is as follows: package com.mkyong.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration; import com.mongodb.Mongo; /** * Spring MongoDB configuration file * */ @Configuration public class SpringMongoConfig extends AbstractMongoConfiguration { @Override public @Bean Mongo mongo() throws Exception { Return new Mongo(“localhost”); } @Override public @Bean MongoTemplate mongoTemplate() throws Exception { Return new MongoTemplate(mongo(),”yourdb”,”yourCollection”); } } 3.2 Method 2 (configuration file method), the code is as follows: <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” xmlns:mOngo=”http://www.springframework.org/schema/data/mongo” xsi:schemaLocation=”http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> 3.3 Writing entity classes package com.mkyong.user; public class User { private String id; private String firstname; private String lastname; private int…