JAVA 자료구조 Spring 몽고DB 연동

2020.09.21 21:51

졸리운_곰 조회 수:182

 

Spring 몽고DB 연동

때로는 특정 정해진 상황과 환경에 맞춰서 코딩작업을 해야하는 경우가 있다. 프로젝트를 시작할때 기본적으로 RDBMS 형태의 MySQL과 NOSQL 몽고디비를같이 사용해야한다. 이때 모든 사이트에서 공통의 소스코드를 공유하기 위해 커스텀작업으로  DB에 데이터를 축적시키는 로직이 필요할때, MySQL을 사용할것인가? 아니면 MongoDB를 사용할 것인다.

 

필자는 MongoDB를 사용하는것이 적합하다고 판단했다. 아무래도 확장성이 좋고, MySQL처럼 테이블을 생성하고 칼럼정의를 해야하는 것보다, 편하게 데이터를 삽입하기 위해 MongoDB를 택했다. 물론 상황에 따라 MySQL을 사용하는것이 적합할때도 있다. 하지만, 기본 솔루션 베이스의 커스텀을 입힌다는 특성상 간단하게 풀어나가는 것이 맞다고 판단한다.

 

pom.xml

mongodb 연동 라이브러리와 object를 json 형태로 변환해주는 gson(선택사항) 라이브러리도 받아준다.

copy xml<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.8.6.RELEASE</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>3.8.0</version>
		</dependency>  
		
		<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
		    <groupId>com.google.code.gson</groupId>
		    <artifactId>gson</artifactId>
		    <version>2.8.1</version>
		</dependency> 

 

home.jsp

CRUD 모두 나열하기는 글이 너무 길어질거 같아 기본적인 통신 부분은 하나씩만 작성하겠다.

기본 틀에 맞춰 코드가 잘 돌아가는지 확인하자.

copy xml<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript">
	function showCollections(){
		$.ajax({
			url:"showCollectionsMongo",
			type:"POST",
			cache:false,
			data:$("#form1").serialize(),
			async:false,
			success:function(data){
				console.log("success");
			},
			error:function(e){
				console.log("err : " + e);
			}
		});
	}
	</script>
</head>
<body>
<button id="insertMongo" onclick="showCollections()">showCollections</button>
</body>
</html>

 

VO Classes

Object 형태로 DB insert하기 위해 여러 형태로 VO class를 만들어 주었다. 최종적으로  Fruit Object로 insert한다.

Fruit.java

copy javapublic class Fruit {
	private String _id;
	private String name;
	private int price;
	private Taste taste;
    }

Taste.java

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

copy javapublic class Taste {
	ArrayList<String> tastes;
	String[] testing;
    }

 

 

MongoService.java

따로 DB를 생성해줄 필요없이, Data생성 기준으로 Database와 Collection이 나뉜다.

조건이 필요한 경우 Query객체와 Criteria객체를 사용하여 조건을 추가해준다.

copy javapackage test.async.mongo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.mongodb.MongoClient;

import test.async.mongo.vo.Fruit;
import test.async.mongo.vo.Taste;

public class MongoService {
	
	private final int MONGO_PORT = 27017;
	private final String MONGO_HOST = "localhost";
	private final String DB_NAME = "testing";
	
	private MongoClient mongo;
	private MongoOperations mongoOps;
	
	//생성시DB와 연동
	public MongoService() {
		mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
		mongoOps = new  MongoTemplate(mongo, DB_NAME);
	}
	
	
	//연결 끊기
	public void close() {
		try {
			mongo.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//DB 컬렉션 모두 출력
	public Set<String> showCollections(){
		return mongoOps.getCollectionNames();
	}
	
	//DB insert
	public void insert(String insertCollection) {
		Fruit fruit = new Fruit();
		fruit.setName("Jamong");
		fruit.setPrice(5000);
		
		Taste taste = new Taste();
		ArrayList<String> tastes = new ArrayList<String>();
		tastes.add("bitter");
		tastes.add("sweet");
		taste.setTastes(tastes);
		
		String[] testing = {"testing1", "testing2"};
		taste.setTesting(testing);
		
		fruit.setTaste(taste);
		
		mongoOps.insert(fruit, insertCollection);
	}
	
	//find one
	public Fruit findOne(String findCollection, Fruit findCondition) {
		Criteria criteria = new Criteria("_id");
		criteria.is(findCondition.get_id());
		
		Query query = new Query(criteria);
		Fruit fruit = mongoOps.findOne(query, Fruit.class, findCollection);
		return fruit;
	}
	
	//find all
	public List<Fruit> findAll(String findCollection){
		return mongoOps.findAll(Fruit.class, findCollection);
	}
	
	//find in condition
	public List<Fruit> findInConditionMongo(String findCollection, Fruit fruit){
		Query query = new Query(new Criteria().andOperator(
				Criteria.where("price").is(fruit.getPrice()),
				Criteria.where("name").is(fruit.getName())
				));
		return mongoOps.find(query, Fruit.class, findCollection);
	}
	
	//remove collection
	public void removeCollection(String deleteCollection) {
		mongoOps.dropCollection(deleteCollection);
	}
	
	//remove data in collection
	public void removeData(String deleteCollection, Fruit condition) {
		Query query = new Query(new Criteria("_id").is(condition.get_id()));
		mongoOps.remove(query, deleteCollection);
	}
}

 

HomeController.java

MongoService객체를 생성하고 로직이 끝난 후 닫는 구조로 되어있다.

Autowired를 사용해도 무방하나, 사용하지 않는 경우 연결을 끊어주기 위해 이렇게 작업했다.

객체형태를 Document구조와 일치시켜주면 자동으로 매핑되서 들어간다.

copy javapackage test.async.mongo.web;

import java.util.ArrayList;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

import test.async.mongo.async.AsyncConfig;
import test.async.mongo.service.AsyncTaskService;
import test.async.mongo.service.MongoService;
import test.async.mongo.vo.Fruit;

@Controller
public class HomeController {

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView home() {
		ModelAndView mav = new ModelAndView("home");
		return mav;
	}
	
	@RequestMapping(value = "/showCollectionsMongo", method = RequestMethod.POST)
	public ModelAndView showCollections() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		Set<String> collections = mongoService.showCollections();
		for(String s : collections) {
			System.out.println("collection ::: " + s);
		}
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/insertMongo", method = RequestMethod.POST)
	public ModelAndView insertMongo() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		mongoService.insert("testData2");
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/findAllMongo", method = RequestMethod.POST)
	public ModelAndView findAllMongo() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		ArrayList<Fruit> fruits = (ArrayList<Fruit>) mongoService.findAll("testData");
		Gson gson = new Gson();
		String result = gson.toJson(fruits);
		System.out.println("result ::: " + result);
		
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/findOneMongo", method = RequestMethod.POST)
	public ModelAndView findMongo() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		Fruit condition = new Fruit();
		condition.set_id("5cb31f0285980309d27af0a8");
		Fruit fruit = mongoService.findOne("testData", condition);
		Gson gson = new Gson();
		String result = gson.toJson(fruit);
		System.out.println("result ::: " + result);
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/findInConditionMongo", method = RequestMethod.POST)
	public ModelAndView findInConditionMongo() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		Fruit condition = new Fruit();
		condition.setPrice(5000);
		condition.setName("Jamong");
		ArrayList<Fruit> fruits = (ArrayList<Fruit>) mongoService.findInConditionMongo("testData2", condition);
		Gson gson = new Gson();
		String result = gson.toJson(fruits);
		System.out.println("result ::: " + result);
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/removeCollection", method = RequestMethod.POST)
	public ModelAndView removeCollection() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		mongoService.removeCollection("testData2");
		mongoService.close();
		return mav;
	}
	
	@RequestMapping(value = "/removeData", method = RequestMethod.POST)
	public ModelAndView removeData() {
		ModelAndView mav = new ModelAndView("jsonView");
		
		MongoService mongoService = new MongoService();
		Fruit condition = new Fruit();
		condition.set_id("5cb31f0285980309d27af0a8");
		mongoService.removeData("testData", condition);
		mongoService.close();
		return mav;
	}
}

[출처] https://myjamong.tistory.com/104

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
38 Spring Batch 간단 정리 Sprong Batch 기초를 알아보자 file 졸리운_곰 2020.10.13 198
37 Spring Batch - ItemReader, ItemWriter, ItemProcessor 졸리운_곰 2020.10.13 370
36 spring batch» Spring Batch Tasklet Example file 졸리운_곰 2020.10.12 198
35 Spring Batch Example 2 - 간단한 Job만들기 file 졸리운_곰 2020.10.12 151
34 Spring batch Job 설정과 실행하기 file 졸리운_곰 2020.10.12 206
33 [Spring Batch] Configuring and Running a Job file 졸리운_곰 2020.10.12 121
32 [스프링] 스프링 배치 기본 개념 file 졸리운_곰 2019.12.24 244
31 Spring Batch 개념 정리 file 졸리운_곰 2019.12.24 257
30 스프링 배치 개발가이드 졸리운_곰 2019.12.24 321
29 Quartz + Spring Batch 조합! Quartz Scheduler 와 Spring Batch 의 궁합과 조합을 정리. file 졸리운_곰 2019.12.24 882
28 Spring Batch 간단 정리 file 졸리운_곰 2019.12.24 421
27 spring batch 소개 file 졸리운_곰 2019.12.24 208
26 Spring Batch - 소개 file 졸리운_곰 2019.12.24 207
25 Spring Batch Multithreading Example file 졸리운_곰 2019.01.31 285
24 Spring batch를 Parallel로 돌려보자 졸리운_곰 2019.01.31 399
23 Spring MVC 주요 애노테이션(Annotation)정리 file 졸리운_곰 2018.12.29 268
22 스프링/스프링부트 애노테이션(Annotation) 정리 졸리운_곰 2018.12.29 385
21 Spring Framework - annotation 정리 #1 졸리운_곰 2018.12.29 321
20 [Spring] Annotation 정리 졸리운_곰 2018.12.29 272
19 Maven 기초 사용법 졸리운_곰 2018.04.15 322
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED