Simple use example of Spring Data MongoDb Repository

Simple use example


of Spring Data MongoDb Repository 1. Using Spring Data MongoDb Repository can save you from writing related query combination statements, it will implement such a class for us internally.
2. As long as you define the interface name according to the regulations, you can save yourself from writing a query combination statement.
3. You can use save only if there is a primary key value (update if there is, insert if not). So it is good to add this field even if there is no ID. (If the id is a String, it will automatically give you an ID number (you can save it without a value), and int requires you to do the only processing and input the value)
4.DATE cannot be used as a primary key.


<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-mongodb</artifactId>
	<version>1.9.3.RELEASE</version>
</dependency>


applicationContext.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"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            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.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">

 <context:annotation-config />
	<!-- <task:annotation-driven /> -->
	<context:component-scan base-package="com" />

    <mongo:mongo host="localhost" port="27017" >
            <!-- If the optional option is not configured, the value is the default -->
          <mongo:options
              connections-per-host="8"
              threads-allowed-to-block-for-connection-multiplier="4"
              connect-timeout="1000"
              max-wait-time="1500"
              auto-connect-retry="true"
              socket-keep-alive="true"
              socket-timeout="1500"
              slave-ok="true"
              write-number="1"
              write-timeout="0"
              write-fsync="true"
                  />
    </mongo:mongo>

    <mongo:db-factory id="anotherMongoDbFactory"
    host="localhost"
    port="27017"
    dbname="admin"
    username="admin"
    password="admin" mongo-ref="mongo"/>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="anotherMongoDbFactory" />
    </bean>

    <!-- The warehouse directory of the mongodb bean will automatically scan the interface extending the MongoRepository interface for injection -->
    <mongo:repositories base-package="com.mongorepository" />

</beans>



package com;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "userTest") //collection specifies the name, not the class name
public class UserTest {

	@Id
	private String id;
        @Indexed(unique = true)
	private String name;
	private String age;
	private String address;
	private String high;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getHigh() {
		return high;
	}

	public void setHigh(String high) {
		this.high = high;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", high=" + high + "]";
	}

}



package com.mongorepository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.UserTest;

public interface UserTestRepository extends MongoRepository<UserTest, String>{
	public UserTest findById(String id); //Just define the interface and define the interface name starting with By
	public List<UserTest> findByName(String name);
}



package com;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.mongorepository.UserTestRepository;

@Service("personService")
public class PersonServiceImpl {
	@Autowired
	private UserTestRepository userTestRepository; //A class that implements this interface will be automatically injected

	@Autowired
	private MongoTemplate mongoTemplate; // easy to implement complex functions

	public UserTestRepository getUserTestRepository() {
		return userTestRepository;
	}

	public void setUserTestRepository(UserTestRepository userTestRepository) {
		this.userTestRepository = userTestRepository;
	}

	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
}


package com;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MongoTest {
	public static void main(String[] args) throws InterruptedException {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");

		PersonServiceImpl personServiceImpl = (PersonServiceImpl) applicationContext.getBean("personService");
		System.out.println(personServiceImpl);

		UserTest userTest = new UserTest();
		userTest.setAddress("setAddress");
		userTest.setName("Name");
		userTest.setAge("setAge");
		userTest.setHigh("setHigh");

		personServiceImpl.getUserTestRepository().insert(userTest);

		List<UserTest> userTestList = personServiceImpl.getUserTestRepository().findAll();
		System.out.println("userTestList == " + userTestList.toString());

		userTestList = personServiceImpl.getUserTestRepository().findByName("Name");
		System.out.println("userTestList == " + userTestList.toString());
	}
}




Reference original text (English reference document): https://docs.mongodb.com/manual/reference/sql-comparison/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940731&siteId=291194637
Recommended