`
sillycat
  • 浏览: 2492647 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

mongodb(3)Mongodb Configuration and Class

 
阅读更多
mongodb(3)Mongodb Configuration and Class

1. Spring XML:
Some concept in Spring data configuration:
<repositories base-package="com.acme.repositories">
  <context:exclude-filter type="regex" expression=".*SomeRepository" />
</repositories>

<repositories base-package="com.acme.repository">
  <repository id="userRepository" repository-impl-ref="customRepositoryImplementation" />
</repositories>

<bean id="customRepositoryImplementation" class="…">
  <!-- further configuration -->
</bean>

interface UserRepositoryCustom {
  public void someCustomMethod(User user);
}
class UserRepositoryImpl implements UserRepositoryCustom {
  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

There are a lot of customized codes and configuration below. But from the blog, the simple example is as follow:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.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/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">

<!-- Activate Spring Data MongoDB repository support -->
  <mongo:repositories base-package="com.sillycat.easynosql.dao.mongodb.repository" />
 
  <!-- MongoDB host -->
<mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}"/>

<!-- Template for performing MongoDB operations -->
  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
  c:mongo-ref="mongo" c:databaseName="${mongo.db.name}"/>

<!-- Service for initializing MongoDB with sample data using MongoTemplate -->
<bean id="initMongoService" class="com.sillycat.easynosql.dao.mongodb.init.InitMongoService" init-method="init"/>
</beans>

2. Annotation in POJO
package com.sillycat.easynosql.model;

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

@Document
public class Role {

@Id
private String id;

private Integer role;
...snip getter and setter...
}

package com.sillycat.easynosql.model;

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

@Document
public class User {

@Id
private String id;

private String firstName;

private String lastName;

private String username;

private String password;

@DBRef
private Role role;
...snip... getter and setter...
}

3. Interface of Repository
Repsitory Lay is the DAO layer, With the help of Spring Data MongoDB, Spring will automatically provide the actual implementation.
Page<User> users = repository.findAll(new PageRequest(1, 20);

There are two main ways that the repository proxy is able to come up with the store specific query from the method name. The first option is to derive the query from the method name directly, the second is using some kind of additionally created query.
User findByUsername(String username);


We will strip the prefixes findBy, find, readBy, read, getBy as well as get from the method and start parsing the rest of it.At a very basic level you can define conditions on entity properties and concatenate them with AND and OR.
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

Page<User> findByLastname(String lastname, Pageable pageable);
List<User> findByLastname(String lastname, Sort sort);
List<User> findByLastname(String lastname, Pageable pageable);

package com.sillycat.easynosql.dao.mongodb.repository;

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

import com.sillycat.easynosql.model.User;

public interface UserRepository extends MongoRepository<User, String> {

User findByUsername(String username);

}

4. InitMongoService to build the init data
package com.sillycat.easynosql.dao.mongodb.init;

import java.util.UUID;

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

import com.sillycat.easynosql.model.Role;
import com.sillycat.easynosql.model.User;

public class InitMongoService {

@Autowired
private MongoTemplate mongoTemplate;

public void init() {
// Drop existing collections
mongoTemplate.dropCollection("role");
mongoTemplate.dropCollection("user");

// Create new records
Role adminRole = new Role();
adminRole.setId(UUID.randomUUID().toString());
adminRole.setRole(1);

Role userRole = new Role();
userRole.setId(UUID.randomUUID().toString());
userRole.setRole(2);

User john = new User();
john.setId(UUID.randomUUID().toString());
john.setFirstName("John");
john.setLastName("Smith");
john.setPassword("111111");
john.setRole(adminRole);
john.setUsername("john");

User jane = new User();
jane.setId(UUID.randomUUID().toString());
jane.setFirstName("Jane");
jane.setLastName("Adams");
jane.setPassword("111111");
jane.setRole(userRole);
jane.setUsername("jane");

// Insert to db
mongoTemplate.insert(john, "user");
mongoTemplate.insert(jane, "user");
mongoTemplate.insert(adminRole, "role");
mongoTemplate.insert(userRole, "role");
}
}

5. UserService to work with the repositories
package com.sillycat.easynosql.service;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sillycat.easynosql.dao.mongodb.repository.RoleRepository;
import com.sillycat.easynosql.dao.mongodb.repository.UserRepository;
import com.sillycat.easynosql.model.User;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

@Autowired
private RoleRepository roleRepository;

public User create(User user) {
user.setId(UUID.randomUUID().toString());
user.getRole().setId(UUID.randomUUID().toString());
roleRepository.save(user.getRole());
return userRepository.save(user);
}

public User read(User user) {
return user;
}

public List<User> readAll() {
return userRepository.findAll();
}

public User update(User user) {
User existingUser = userRepository.findByUsername(user.getUsername());

if (existingUser == null) {
return null;
}

existingUser.setFirstName(user.getFirstName());
existingUser.setLastName(user.getLastName());
existingUser.getRole().setRole(user.getRole().getRole());

roleRepository.save(existingUser.getRole());
return userRepository.save(existingUser);
}

public Boolean delete(User user) {
User existingUser = userRepository.findByUsername(user.getUsername());

if (existingUser == null) {
return false;
}

roleRepository.delete(existingUser.getRole());
userRepository.delete(existingUser);
return true;
}

}

references:
http://feiyan35488.iteye.com/blog/763165
http://qljcly.iteye.com/blog/703714
http://liureying.blog.163.com/blog/static/6151352011030433930/
http://gundumw100.iteye.com/blog/452221
http://static.springsource.org/spring-data/data-mongodb/docs/current/reference/html/


分享到:
评论

相关推荐

    Practical.MongoDB.Architecting.Developing.and.Administering.MongoDB

    Chapter 5: MongoDB - Installation and Configuration Chapter 6: Using MongoDB Shell Chapter 7: MongoDB Architecture Chapter 8: MongoDB Explained Chapter 9: Administering MongoDB Chapter 10: MongoDB Use...

    Mastering MongoDB 3.x

    The book is based on MongoDB 3.x and covers topics ranging from database querying using the shell, built in drivers, and popular ODM mappers to more advanced topics such as sharding, high ...

    MongoDB and Python Patterns and processes

    MongoDB and Python Patterns and processes for the popular document-oriented database

    深入学习MongoDB:Scaling MongoDB && 50 Tips and Tricks for MongoDB Developers

    深入学习MongoDB:Scaling MongoDB && 50 Tips and Tricks for MongoDB Developers深入学习MongoDB中文版Scaling MongoDB英文版50 Tips and Tricks for MongoDB Developers英文版高清完整目录3本打包合集

    Big.Data.NoSQL.Architecting.MongoDB.epub

    Chapter 5: MongoDB – Installation and Configuration Chapter 6: Using Mongo Shell Chapter 7: MongoDB Explained Chapter 8: Administering MongoDB Chapter 9: MongoDB Use Cases Chapter 10: MongoDB How To'...

    MongoDB and Python

    Python MongoDB 应用开发,构建高效稳定数据库应用系统

    MongoDB The Definitive Guide 3rd Edition

    Authors Shannon Bradshaw (MongoDB) and Kristina Chodorow (Google) provide guidance for database developers, advanced configuration for system administrators, and use cases for a variety of projects....

    The.Definitive.Guide.to.MongoDB.3rd.Edition.1484211839

    The Definitive Guide to MongoDB, Third Edition, is updated for MongoDB 3 and includes all of the latest MongoDB features, including the aggregation framework introduced in version 2.2 and hashed ...

    Web.Development.with.MongoDB.and.NodeJS.2nd.Edition.178528752

    Chapter 3: Node and MongoDB Basics Chapter 4: Introducing Express Chapter 5: Templating with Handlebars Chapter 6: Controllers and View Models Chapter 7: Persisting Data with MongoDB Chapter 8: ...

    MongoDB笔记.docx

    一、MongoDB简介 3 二、MongoDB结构 3 二、MongoDB 数据库关系型(这里并不是值关系型数据库的关系) 3 1、MongoDB一对一关系型 3 2、MongoDB一对多关系型 4 3、MongoDB多对多关系型 4 三、创建数据库(mongodb_test...

    tigase 7.10 mongodb 3 配置

    tigase 7.10 mongodb 3 配置

    MongoDB_and_Python.pdf.pdf

    MongoDB_and_Python.pdf

    Mongodb结合D3数据展示

    Mongodb 10亿级数据实时查询的小示例,还是很快的

    Web Development with MongoDB and Node(3rd) epub

    Web Development with MongoDB and Node(3rd) 英文epub 第3版 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    mongodb-linux-x86_64-4.0.18.tgz

    3、进入 mongodb 目录创建目录 db 和 logs cd /usr/local/mongodb mkdir db mkdir logs 4、进入到 bin 目录下,编辑 mongodb.conf 文件,内容如下: dbpath=/usr/local/mongodb/db logpath=/usr/local/mongodb/...

    MongoDB图形化管理工具 MongoDB Compass

    MongoDB图形化管理工具 MongoDB Compass

    MongoDB The Definitive Guide

    the company that develops and supports this open source database, MongoDB: The Definitive Guide provides guidance for database developers, advanced configuration for system administrators, and an ...

    Linux安装mongodb客户端

    sudo vim /etc/yum.repos.d/mongodb-org-4.2.repo 写入: [mongodb-org-4.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/ gpgcheck=1 enabled=1 gpg...

    MongoDB.Data.Modeling.1782175342

    Focus on data usage and better design schemas with the help of MongoDB About This Book Create reliable, scalable data models with MongoDB Optimize the schema design process to support applications of...

    MongoDB应用设计模式

    资源名称:MongoDB应用设计模式内容简介:无论是在构建社交媒体网站,还是在开发一个仅在内部使用的企业应用程序,《MongoDB应用设计模式》展示了MongoDB需要解决的商业问题之间的连接。你将学到如何把MongoDB设计...

Global site tag (gtag.js) - Google Analytics