- 浏览: 2552000 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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/
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/
发表评论
-
Stop Update Here
2020-04-28 09:00 316I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 476NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 369Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 370Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 337Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 431Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 374Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 455VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 478NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 423Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 248GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 451GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 319Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ...
相关推荐
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { GsonHttpMessageConverter ...
public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean public ...
**3. 创建MongoDB配置类** 虽然SpringBoot自动配置能处理大部分工作,但有时我们可能需要自定义配置,如设置MongoDB的副本集或认证信息。这可以通过创建一个@Configuration类来实现: ```java @Configuration ...
public class MongoDBConfig { @Autowired private MongoProperties mongoProperties; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoProperties.getUri()); } @Bean public...
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean"> ``` 或者使用Java配置: ```java @Configuration public class MongoConfig { @Value("${mongo.host:localhost}") ...
public class MongoDBConfig { @Bean(name = "mongoTemplate1") @ConfigurationProperties(prefix = "spring.data.mongodb") public MongoTemplate mongoTemplate1(MongoDbFactory dbFactory1) { return new ...
3. **实体类(Mapping)**: 在使用Spring Data MongoDB时,通常需要创建Java对象(称为Document)来映射MongoDB的集合。这些类通常使用`@Document`注解来标识,并且可以通过`@Id`注解指定主键字段。 ```java @...
@Configuration public class MongoConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean ...
@Configuration @ConfigurationProperties(prefix = "spring.data.mongodb") public class MongoConfig { private String host; private int port; private String database; // getters and setters } ``` ...
public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean public ...
public class MongoDBConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoTemplate mongoTemplate() throws Exception { MongoClient mongoClient = MongoClients....
public class MongoDBConfig { @Autowired private Mongo mongo; @Bean public MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongo, "test"); } } ``` 然后,可以使用 `...
MongoDB 是一个流行的开源、高性能、无模式的文档型数据库,常用于构建现代分布式应用程序。在Spring Boot框架中集成MongoDB,可以方便地管理和操作数据。"MongoDB 配置多数据源"意味着我们需要在同一个应用中配置多...
**3. 创建实体类** 在 Spring Boot 中,我们将 MongoDB 的集合映射为 Java 类,通常使用 `@Document` 注解来标识。例如,创建一个名为 `User` 的实体类: ```java import org.springframework.data.annotation.Id;...
MongoClient mongoClient = Mongo.create("mongodb://" + Play.application().configuration().getString("mongodb.uri")); Datastore datastore = morphia.createDatastore(mongoClient, Play.application()....
**3. 使用MongoRepository** Spring Data MongoDB提供了一个强大的`MongoRepository`接口,它扩展了`PagingAndSortingRepository`,可以处理分页和排序。只需为你的实体类型定义一个接口,继承`MongoRepository`,...
3. **更新(Update)**: 更新操作可以使用`updateFirst()`, `updateMultiplte()`等方法。例如,更新一个用户的年龄: ```java Query query = new Query(Criteria.where("id").is(userId)); Update update = new ...
@Configuration public class MongoConfig { @Value("${spring.data.mongodb.uri}") private String mongoUri; @Bean public MongoClient mongoClient() { return MongoClients.create(mongoUri); } @Bean...
3. 创建Repository接口并定义查询方法。 4. 实现服务类,通过Repository接口进行数据操作。 5. 使用MongoTemplate进行更灵活的数据操作(可选)。 通过这种方式,Spring Boot使得与MongoDB的集成变得简单且高效,极...
1. **实体类(Entity Class)**: 用于表示MongoDB中的文档,通常是一个Java类,其字段对应于MongoDB文档的字段。使用注解来指定字段映射,比如`@Id`用于标识主键,`@DBRef`用于处理引用其他文档的关系。 2. **继承...