spring data mongodb基礎篇

學習階段能夠安裝一個windows版本的mongodb,儘快把mongodb服務跑起來,讓程序連上。mongodb的安裝、運行、基礎命令的知識,能夠參考 菜鳥教程mongodbhtml

spring mongodb 依賴版本:spring版本是4.0.9.RELEASEjava

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

spring mongodb的配置正則表達式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/data/mongo
    http://www.springframework.org/schema/data/mongo/spring-mongo-1.7.xsd  ">

	<context:component-scan base-package="com.wss.lsl.pay.demo">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- mongo config start -->
	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
	    <property name="host" value="192.168.1.134" />
	    <property name="port" value="27017" />
	</bean>
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
	    <constructor-arg name="mongo" ref="mongo" />
	    <constructor-arg name="databaseName" value="test" />
	</bean>
	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
	<mongo:repositories base-package="com.wss.lsl.pay.demo.dao" mongo-template-ref="mongoTemplate" />	
	<!-- mongo config end -->	
</beans>

領域對象:model實體spring

package com.wss.lsl.pay.demo.model;

import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import com.mysema.query.annotations.QueryEntity;
import com.wss.lsl.pay.demo.common.annotation.CascadeSave;

// 複合索引
@CompoundIndexes({ @CompoundIndex(name = "name_1_age_1", def = "{'name': 1, 'age': 1}") })
@Document(collection = "user")
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	private String id;

	private String name;

	@Field("age") // 保存在數據庫的別名
	private int age;

	@Indexed // 單字段索引
	private Integer yearOfBirth;

	@Transient // 不持久化在數據庫
	private String password;
	
	// getter/setter
}

dao寫法mongodb

package com.wss.lsl.pay.demo.dao;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;

import com.wss.lsl.pay.demo.model.User;

public interface UserRepository extends MongoRepository<User, String>, QueryDslPredicateExecutor<User> {
	
	// 根據名字查詢用戶列表	
	List<User> findByName(String name);
	
	// 查詢名字以什麼開頭的用戶列表	
	List<User> findByNameStartingWith(String regexp);
	
	//查詢名字以什麼結尾的用戶列表	 
	List<User> findByNameEndingWith(String regexp);
	
	// 查詢年齡區間的用戶列表
	// ageLt < age < ageGt	 
	List<User> findByAgeBetween(int ageLt, int ageGt);
	
	// 查詢名字包含。全模糊查詢 
	List<User> findByNameLike(String name);
	
	// 多條件組合查詢
	// 查詢名字包含<br>
	// 結果集按age升序排
	List<User> findByNameLikeOrderByAgeAsc(String name);
	
	// 註解方式查詢。按名字查詢用戶
	// ?0表示第一個參數
	@Query("{'name': ?0}")
	List<User> findUsersByName(String name);
	
	// 根據用戶名字的正則表達式查詢$regex
	@Query("{'name':{$regex: ?0}}")
	List<User> findUsersByRegexpName(String regexp);
	
	// 根據年齡區間查詢	
	@Query("{'age':{$gt:?0, $lt: ?1}}")
	List<User> findUsersByAgeBetween(int ageGT, int ageLT);	
}

單元測試數據庫

package com.wss.lsl.pay.demo.dao;

import java.util.List;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mysema.query.types.Predicate;
import com.wss.lsl.pay.demo.model.Card;
import com.wss.lsl.pay.demo.model.QUser;
import com.wss.lsl.pay.demo.model.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/META-INF/spring/applicationContext.xml"})
public class UserRepositoryTest {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private MongoTemplate mongoTemplate;

	@Before
	public void setUp() {
		userRepository.deleteAll(); // 清空數據,爲測試用例準備前提條件
	}

	@After
	public void after() {
	}

	private void saveUser(String name, int age) {
		User user = new User(name, age);
		userRepository.insert(user);
	}

	private User getLongNameUser() {
		return new User("張三32323rtyuioghjklsadas範德", 20);
	}

	// 測試插入
	@Test
	public void testInsert() throws InterruptedException {
		int count = 100;
		for (int i = 0; i < count; i++) {
			User user = getLongNameUser();
			userRepository.insert(user);
		}

		// 校驗插入的數據數量
		long totalCount = userRepository.count();
		Assert.assertEquals(count, totalCount);
	}

	// 測試查詢
	@Test
	public void testQuery() {
		User user = new User("張三", 20);
		userRepository.insert(user);

		user = new User("李四", 20);
		userRepository.insert(user);

		// page 從0開始
		Pageable page = new PageRequest(0, 2, Direction.ASC, "name");
		Page<User> list = userRepository.findAll(page);
		List<User> users = list.getContent();
		User zhangsan = users.get(0);
		User lisi = users.get(1);

		Assert.assertEquals("張三", zhangsan.getName());
		Assert.assertEquals("李四", lisi.getName());

		// 按名字查詢
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is("張三"));
		users = mongoTemplate.find(query, User.class);
		Assert.assertEquals(1, users.size());

		query = new Query();
		query.addCriteria(Criteria.where("name").is("李四"));
		users = mongoTemplate.find(query, User.class);
		Assert.assertEquals(1, users.size());
	}

	// 測試更新
	@Test
	public void testUpdate() {
		long count = userRepository.count();
		Assert.assertEquals(0, count);

		User user = new User("張三", 20);
		userRepository.save(user); // 沒有先插入
		// 校驗
		count = userRepository.count();
		Assert.assertEquals(1, count);
		user = userRepository.findOne(user.getId());
		Assert.assertEquals("張三", user.getName());

		// 更新操做
		user.setName("張三2");
		userRepository.save(user);
		// 校驗
		count = userRepository.count();
		Assert.assertEquals(1, count);
		user = userRepository.findOne(user.getId());
		Assert.assertEquals("張三2", user.getName());
	}

	// 測試刪除操做
	@Test
	public void testDelete() {
		User user = new User("張三", 20);
		userRepository.insert(user);

		user = new User("李四", 30);
		userRepository.insert(user);

		// 刪除了「李四」
		mongoTemplate.remove(user, "user");

		// 校驗只有「張三」
		List<User> users = mongoTemplate.findAll(User.class);
		Assert.assertEquals(1, users.size());
		Assert.assertEquals("張三", users.get(0).getName());
	}

	// 測試between查詢
	@Test
	public void testBetween() {
		saveUser("張三", 20);
		saveUser("李四", 25);
		saveUser("王五", 31);

		List<User> users = userRepository.findByAgeBetween(20, 30);
		Assert.assertEquals(1, users.size());
		Assert.assertEquals("李四", users.get(0).getName());
	}

	// 測試like
	@Test
	public void testLike() {
		saveUser("三張", 20);
		saveUser("李五四三", 30);
		saveUser("王三五", 31);

		List<User> users = userRepository.findByNameLike("三");
		Assert.assertEquals(3, users.size());
		for (User user : users) {
			Assert.assertTrue(user.getName().contains("三"));
		}
	}

	// 測試排序:按年齡排序
	@Test
	public void testSort() {
		saveUser("三張", 20);
		saveUser("王三五", 31);
		saveUser("李五四三", 30);
		saveUser("李五四三", 10);
		saveUser("李五四三", 30);

		List<User> users = userRepository.findByNameLikeOrderByAgeAsc("三");
		Assert.assertEquals(5, users.size());
		Assert.assertEquals(10, users.get(0).getAge());
		Assert.assertEquals(20, users.get(1).getAge());
		Assert.assertEquals(30, users.get(2).getAge());
		Assert.assertEquals(30, users.get(3).getAge());
		Assert.assertEquals(31, users.get(4).getAge());
	}		
}
相關文章
相關標籤/搜索