`
sillycat
  • 浏览: 2551729 次
  • 性别: 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/


分享到:
评论

相关推荐

    SpringBoot mongoDB 项目 [免费]

    @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters) { GsonHttpMessageConverter ...

    springboot整合mongodb changestream代码

    public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean public ...

    SpringBoot集成MongoDB

    **3. 创建MongoDB配置类** 虽然SpringBoot自动配置能处理大部分工作,但有时我们可能需要自定义配置,如设置MongoDB的副本集或认证信息。这可以通过创建一个@Configuration类来实现: ```java @Configuration ...

    MongoDB初探(二)----使用spring-data配置mongodb

    public class MongoDBConfig { @Autowired private MongoProperties mongoProperties; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoProperties.getUri()); } @Bean public...

    spring-mongodb整合源码 注释

    &lt;bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean"&gt; ``` 或者使用Java配置: ```java @Configuration public class MongoConfig { @Value("${mongo.host:localhost}") ...

    Sping boot MongoDB 配置多数据源

    public class MongoDBConfig { @Bean(name = "mongoTemplate1") @ConfigurationProperties(prefix = "spring.data.mongodb") public MongoTemplate mongoTemplate1(MongoDbFactory dbFactory1) { return new ...

    mongodb在java中小试牛刀

    3. **实体类(Mapping)**: 在使用Spring Data MongoDB时,通常需要创建Java对象(称为Document)来映射MongoDB的集合。这些类通常使用`@Document`注解来标识,并且可以通过`@Id`注解指定主键字段。 ```java @...

    springboot集成mongodb增删改查功能源码

    @Configuration public class MongoConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean ...

    MongoDB与Spring整合

    @Configuration @ConfigurationProperties(prefix = "spring.data.mongodb") public class MongoConfig { private String host; private int port; private String database; // getters and setters } ``` ...

    Spring Mongodb Maven示例

    public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean public ...

    spring-mongodb整合

    public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoTemplate mongoTemplate() throws Exception { MongoClient mongoClient = MongoClients....

    Spring Boot使用MongoDB详解

    public class MongoDBConfig { @Autowired private Mongo mongo; @Bean public MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongo, "test"); } } ``` 然后,可以使用 `...

    MongoDB 配置多数据源

    MongoDB 是一个流行的开源、高性能、无模式的文档型数据库,常用于构建现代分布式应用程序。在Spring Boot框架中集成MongoDB,可以方便地管理和操作数据。"MongoDB 配置多数据源"意味着我们需要在同一个应用中配置多...

    mongodb与springboot集成例子

    **3. 创建实体类** 在 Spring Boot 中,我们将 MongoDB 的集合映射为 Java 类,通常使用 `@Document` 注解来标识。例如,创建一个名为 `User` 的实体类: ```java import org.springframework.data.annotation.Id;...

    play1.x连接mongodb

    MongoClient mongoClient = Mongo.create("mongodb://" + Play.application().configuration().getString("mongodb.uri")); Datastore datastore = morphia.createDatastore(mongoClient, Play.application()....

    spring +mongodb

    **3. 使用MongoRepository** Spring Data MongoDB提供了一个强大的`MongoRepository`接口,它扩展了`PagingAndSortingRepository`,可以处理分页和排序。只需为你的实体类型定义一个接口,继承`MongoRepository`,...

    mongodb之CRUD小demo

    3. **更新(Update)**: 更新操作可以使用`updateFirst()`, `updateMultiplte()`等方法。例如,更新一个用户的年龄: ```java Query query = new Query(Criteria.where("id").is(userId)); Update update = new ...

    征服 Mongodb 之 Spring相关实现(一)

    @Configuration public class MongoConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean...

    配置和实验springboot与第三方技术的集成 入springboot+mongodb.zip

    3. 创建Repository接口并定义查询方法。 4. 实现服务类,通过Repository接口进行数据操作。 5. 使用MongoTemplate进行更灵活的数据操作(可选)。 通过这种方式,Spring Boot使得与MongoDB的集成变得简单且高效,极...

    基于mongodb官方Java驱动的orm框架,允许子类嵌套.zip

    1. **实体类(Entity Class)**: 用于表示MongoDB中的文档,通常是一个Java类,其字段对应于MongoDB文档的字段。使用注解来指定字段映射,比如`@Id`用于标识主键,`@DBRef`用于处理引用其他文档的关系。 2. **继承...

Global site tag (gtag.js) - Google Analytics