JavaでMongoDB接続を取得する方法詳細
まず必要なjarカバンです。Mavenの中の配置は以下の通りです。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.9.1</version>
</dependency>
接続コードの取得は以下の通りです。
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(new ServerAddress(dataSource.getSourceIp(), Integer.valueOf(dataSource.getSourcePort())));
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(MongoCredential.createScramSha1Credential(dataSource.getUsername(), dataSource.getSourceName(), dataSource.getPassword().toCharArray()));
MongoClient mongoClient = new MongoClient(addrs, credentials);
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, dataSource.getSourceName());
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
mongoTemplate.getCollectionNames();
または次のように取得します。
ServerAddress serverAddress = new ServerAddress("192.168.16.121",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()
MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "123456Ab".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
// MongoDB
MongoClient mongoClient = new MongoClient(addrs,credentials);
//
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
mongoDatabase.getCollection("test").find().iterator();
//
mongoClient.close();
簡単な添削の例を添付します。
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
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 com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;
import bean.Book;
import bean.Good;
import bean.ShopDO;
import net.sf.json.JSONObject;
public class MongoTemplateTest {
public static MongoTemplate mongoTemplate = getMongoTemplate();
public static void main(String[] args) {
System.out.println(mongoTemplate.getCollectionNames());
}
public static MongoTemplate getMongoTemplate(){
String host = "192.168.16.121";
int port = 27017;
String databaseName = "test";
String username = "root";
String password = "123456Ab";
//ServerAddress(host,port) IP
ServerAddress serverAddress = new ServerAddress(host,port);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential(username,source,password)
MongoCredential credential = MongoCredential.createScramSha1Credential(username, databaseName, password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
// MongoDB
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
return mongoTemplate;
}
/**
*
*/
@Test
public void save(){
ShopDO shop1 = new ShopDO(100L," ");
ShopDO shop2 = new ShopDO(101L," ");
mongoTemplate.save(shop1,"col");
mongoTemplate.save(shop2,"col");
System.out.println("mongoDB , col, :"+mongoTemplate.getCollection("col"));
}
@Test
public void save1(){
Book book = new Book(22L," ","32.5");
mongoTemplate.save(book,"col");
}
@Test
public void save2(){
Good good = new Good(new HashMap<String,String>(){{put("id","1");put("name"," ");}});
mongoTemplate.save(good,"col");
}
@Test
public void save3(){
mongoTemplate.save(JSONObject.fromObject("{\" \":\"we\",\" \":\"hai\"}"),"col");
System.out.println("mongoDB , col, :"+mongoTemplate.getCollection("col"));
}
/**
*
*/
@Test
public void findAll(){
List<ShopDO> list = mongoTemplate.findAll(ShopDO.class,"col");
System.out.println("mongoDB , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
}
/**
*
*/
@Test
public void simpleQuery(){
Query query = Query.query(Criteria.where("no").is(100L));
List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
System.out.println("mongoDB ID , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
}
/**
*
*/
@Test
public void muchQuery(){
Criteria criteria = new Criteria();
//or ,and
criteria.orOperator(
Criteria.where("no").is(100),
Criteria.where("name").is(" "));
Query query = new Query(criteria); // query
Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"no")); //
query.with(sort);
List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
System.out.println("mongoDB , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
}
/**
*
*/
@Test
public void LimitQuery(){
Query query = new Query();
query.skip(1).limit(3);
List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
System.out.println("mongoDB 1 3 , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
}
/**
*
*/
@Test
public void LikeQuery(){
Query query = new Query(Criteria.where("name").regex(" "));
List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
System.out.println("mongoDB , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
Update update = new Update();
update.set("name"," old");
WriteResult wr = mongoTemplate.updateMulti(query,update,"col");
System.out.println("mongoDB , col, :" + wr.getN());
}
/**
*
*/
@Test
public void update(){
Query query = new Query(Criteria.where("no").is(100));
List<ShopDO> list = mongoTemplate.find(query,ShopDO.class,"col");
System.out.println("mongoDB no 100 , col, :");
for (ShopDO shopDO:list){
System.out.println(shopDO.getNo()+"/"+shopDO.getName());
}
Update update = new Update();
update.set("name"," new");
WriteResult wr = mongoTemplate.updateFirst(query,update,"col");
System.out.println("mongoDB , col, :" + wr.getN());
}
/**
*
*/
@Test
public void delete(){
Query query = new Query(Criteria.where("no").is(1));
WriteResult result = mongoTemplate.remove(query, "col");
System.out.println("mongoDB , col, :" + result.getN() + " ID "+result.getUpsertedId());
}
}
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。