티스토리 뷰

이전 포스팅에서 설명한 Repository 인터페이스중에 PagingAndSortingRepository 를 이용해서 MongoDB 데이터에 접근해보자. PagingAndSortingRepository 는 CrudRepository 인터페이스를 상속받기 때문에 기본적인 CRUD 메소드를 가지고 있으며, 추가적으로 페이징 처리에 필요한 메소드를 가지고 있어서 아마도 자주 쓰게 될 Repository 인터페이스가 아닐까 싶다.



Domain Class


com.springdata.domain 패키지를 하나 추가하고, 그 안에 도메인 클래스를 하나 만든다.

package com.springdata.domain;

import org.springframework.data.annotation.Id;

public class Person {

	@Id
	private String id;
	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}


Repository Interface


com.springdata.repository 패키지를 하나 만들고, 그 안에 PersonRepository 인터페이스를 만든다. 여기서는 PagingAndSortingRepository 를 이용해서 만들었다.

package com.springdata.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import com.springdata.domain.Person;

public interface PersonRepository extends PagingAndSortingRepository<Person, String> {

}

미리 만들어놓은 Person 도메인객체를 기입하고, ID 값은 String 형식으로 정해놓았다. ID 값은 BigInteger, Long 형 여러가지로 선언해 쓸 수가 있던데.. 우선 여기서는 String 형식으로 하자. 인터페이스안에 아직 아무것도 선언하지는 않았지만, Person 데이터들을 접근할 기본 CRUD 메소드를 가진 Repository 를 만든 것이다.



Spring configuration


root-context.xml 파일에 아래 mongo:repositories 정보를 추가한다.

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        	http://www.springframework.org/schema/data/mongo
        	http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
    <mongo:mongo host="localhost" port="27017" />
     
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo"/>
        <constructor-arg name="databaseName" value="test"/>
    </bean>
    
    <mongo:repositories base-package="com.springdata.repository" />
</beans>

이렇게 해서 Repository 를 사용하기위한 준비는 끝이다. paging 처리가 굳이 필요없다면 CrudRepository 인터페이스를 상속받아서 사용해도 된다. 아래 그림은 참고로 패키지가 잘 정리되있는지 확인용.




반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함