6. mongoDB的java客户端


1. springboot操作mongodb


1. maven配置


      
org.springframework.boot    
spring-boot-starter-data-mongodb

2. application.properties中添加配置

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

多个IP集群的可以采用下面的配置:

spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

3. 创建数据库操作的实体类

import java.io.Serializable;
public class User implements Serializable {
      private static final long serialVersionUID = -3258839839160856613L;
      private Long id;
      private String userName;
      private String passWord;

      public Long getId() {
              return id;
      }

      public void setId(Long id) {
              this.id = id;
      }

      public String getUserName() {
              return userName;
      }

      public void setUserName(String userName) {
              this.userName = userName;
      }

      public String getPassWord() {
              return passWord;
      }

      public void setPassWord(String passWord) {
              this.passWord = passWord;
      }

      @Override
      public String toString() {
              return "UserEntity{" +
                      "id=" + id +
                      ", userName='" + userName + '\'' +
                      ", passWord='" + passWord + '\'' +
                      '}';
      }
}

4. 实体类相关的增删改查操作

import com.mongodb.client.result.UpdateResult;
import com.neo.repository.UserRepository;
import com.neo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class UserRepositoryImpl implements UserRepository {

  @Autowired
  private MongoTemplate mongoTemplate;

  /**
    * 创建对象
    * @param user
    */
  @Override
  public void saveUser(User user) {
      mongoTemplate.save(user);
  }

  /**
    * 根据用户名查询对象
    * @param userName
    * @return
    */
  @Override
  public User findUserByUserName(String userName) {
      Query query=new Query(Criteria.where("userName").is(userName));
      User user = mongoTemplate.findOne(query , User.class);
      return user;
  }

  /**
    * 更新对象
    * @param user
    */
  @Override
  public long updateUser(User user) {
      Query query=new Query(Criteria.where("id").is(user.getId()));
      Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
      //更新查询返回结果集的第一条
      UpdateResult result =mongoTemplate.updateFirst(query,update,User.class);
      //更新查询返回结果集的所有
      // mongoTemplate.updateMulti(query,update,UserEntity.class);
      if(result!=null)
          return result.getMatchedCount();
      else
          return 0;
  }

  /**
    * 删除对象
    * @param id
    */
  @Override
  public void deleteUserById(Long id) {
      Query query=new Query(Criteria.where("id").is(id));
      mongoTemplate.remove(query,User.class);
  }
}

2. 多数据源MongoDB的使用

1. Maven配置

      
org.springframework.boot    
spring-boot-starter-data-mongodb

2. 配置两条数据源

mongodb:
primary:
  host: localhost
  port: 27017
  database: test
secondary:
  host: localhost
  port: 27017
  database: data

3. 创建文件实体类

import lombok.Data;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;

@Data //生成get、set方法等
public class MultipleMongoProperties {

  private MongoProperties primary = new MongoProperties();
  private MongoProperties secondary = new MongoProperties();

}

4. 配置两个数据库

数据库1

@Configuration
@EnableMongoRepositories(basePackages = "com.tedu.huawei.repository.primary",
      mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE) //basePackages对应第一个库的repository所在的地址
public class PrimaryMongoConfig {
  protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}

数据库2

@Configuration
@EnableMongoRepositories(basePackages = "com.tedu.huawei.repository.secondary",
      mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {
  protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}

5. 构造对应的MongoTemplate

import com.mongodb.MongoClient;
import com.tedu.huawei.entity.MultipleMongoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

@Configuration
public class MultipleMongoConfig {

  @Autowired
  private MultipleMongoProperties mongoProperties;

  @Bean
  @ConfigurationProperties(prefix = "mongodb")
  public MultipleMongoProperties connectionSettings(){
      return new MultipleMongoProperties();

  }

  @Primary
  @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
  public MongoTemplate primaryMongoTemplate() throws Exception {
      return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
  }

  @Bean
  @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
  public MongoTemplate secondaryMongoTemplate() throws Exception {
      return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
  }

  @Bean
  @Primary
  public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {
      return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
              mongo.getDatabase());
  }

  @Bean
  public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception {
      return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
              mongo.getDatabase());
  }
}