Spring Data MongoDb Repository 简单使用例子

SpringDataMongoDbRepository简单使用例子

1.使用SpringDataMongoDbRepository可以使你不用写相关的查询组合语句,它会内部为我们实现这样的一个类。

2.只要你按规定定义好接口名就可以免去你写查询组合语句。

3.要有主键值才可以用save(有就更新,没有就插入)。所以就算没有ID也增加这个字段是好的。(id要是String才会自动为你生面ID号(保存时可以没有值),int要你自己做惟一处理和输入值)

4.DATE不能作为主键使用。

<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" >
            <!-- 可选项如果不配置则为值为默认 -->
          <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>

    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
    <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指定名字,不指定为类名
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);			//只定义接口就可以了,以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;  //会自动注入实现这个接口的类

	@Autowired
	private MongoTemplate mongoTemplate; // 方便复杂功能实现

	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());
	}
}

参考原文(英文参考文档):https://docs.mongodb.com/manual/reference/sql-comparison/

相关推荐