Crea un api REST de la forma más simple con Java y Spring Data REST
Aprende la forma más simple de escribir un API REST con Java utilizando Spring Data REST !
En posts anteriores se explicó como hacer una API rest utilizando Spring Data, Spring REST y Spring Boot, en este post se explicará una forma aún más simple de hacerlo haciendo uso de Spring Data REST.
1. Configuración
El primer paso será crear un proyecto Maven que tenga como padre el siguiente proyecto:
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
Repository는 data를 저장하는 역활을 하는 모든 객체를 추상화한 단어로 생각하면 된다. 실제 구체적인 예는 아래와 같다.
DBMS - database
File System - File
NoSQL - database
그리고 Repository에 저장될 객체의 유형(타입)은 보통 Generic을 사용하여 선언한다. 아래의 예제에서 Generic 선언은 <user>이다.
예) UserRepository<user>
위의 예를 풀어서 말하면, User타입의 객체를 저장하는 UserRepository로 말할 수 있다.
Spring data와 MongoDB
Spring data는 MongoDB와 연동하기 위해 MongoRepository interface를 제공한다. 이에 대한 하위 구현 class는 아래와 같다.
org.springframework.data.mongodb.repository.support.SimpleMongoRepository: MongoRepository의 기본 구현 클래스로 save, insert, findAll 메서드등 에 대한 구현을 모두 포함하고 있다. 직접 Repository interface를 선언하여 사용할 경우, SimpleMongoRepository가 proxy객체로 사용된다.
How to use
Basic use
아래와 같이 직접 Repository를 정의하여 사용할 수 있다. 아래의 예제에서 MongoRepository<user string> 에 사용된 첫번째(User) generic type은 repository가 저장할 객체의 타입을 말하며, 두번째(String)은 User 객체의 id값의 타입을 말한다.
@RepositoryRestResource( collectionResourceRel = "services", // collection을 mapping한다. path = "services" ) public interface UserRepository extends MongoRepository<user string> { public User findById(String id); public Page<user> findByNameLike(String name); }
위와 같이 MongoRepository를 상속받는 interface만을 선언해 놓으면 spring data에서 나머지는 알아서 처리해준다. 즉, 다른 객체에서 UserRepository. findByNameLike를 호출하게 되면 주어진 name과 유사한 User들을 반환해 준다. interface의 구현 class를 직접 작성하지 않아도 된다는 것이다.
Custom Use#1
Basic use 와 같이 spring data에서 제공하는 기본기능만을 사용해도 되지만, 세상이 늘 그렇게 쉽지 많은 않다. 예를 들어 사용자의 나이를 기준으로 몇세 이하, 몇세 이상등의 특정 use case에 맞는 조회를 해야 하는 경우가 실제에선 비일비재하게 생기게 마련이다.
이런 경우 아래의 UserRepositoryCustom 같이 특정 use case에 필요한 메서드를 포함하고 있는 interface를 선언하고 이를 구현하는 구현 class를 선언하면 된다. 구현 class의 이름에 유의해야 한다. 반드시 MongoRepository를 상속한 repository의 이름(UserRepository) + "Impl"로 선언해야 spring data에서 자동으로 인식한다.
public class UserRepositoryImpl implements UserRepositoryCustom { @Autowired MongoTemplate mongoTemplate; Page<user> findByAgeLessThanEqual(int age) { Pageable pageable = new PageRequest(0, 100); //pageNo, rowCount per page Query query = new Query( Criteria.where("age").lte(age) //lte -> less then equal ); long totalCount = mongoTemplate.count(query, User.class); List<user> userList = mongoTemplate.find(query, User.class); return new PageImpl(userList, pageable, totalCount); } }
마지막으로 UserRepository를 UserRepositoryCustom의 하위interface로 만들어 준다.
@RepositoryRestResource( collectionResourceRel = "services", // collection을 mapping한다. path = "services" ) public interface UserRepository extends MongoRepository<user string>, UserRepositoryCustom { public User findById(String id); public Page<user> findByNameLike(String name); }
Custom Use#2
Custom Use#1는 실제로 Custom interface를 사용하지 않아도 된다. 왜냐면 age의 경우 보통 원시(primitive)타입이기때문이다. custom interface없이 그냥 findByAgeLessThan이렇게 UserRepository에 선언만 해줘도 spring data가 알아서 해준다.
쿼리 메서드 선언 유형 확인
하지만 세상이 그렇게 쉬운가? 클래스를 정의할때 원시 타입의 변수만 있으면 얼마나 좋겠나. 또 다른 클래스로 선언된 객체를 참조하는 참조 타입의 변수를 사용할 경우는 위에서 한 것처럼 custom interface를 선언하여 사용해야 한다.
예를 들어 User클래스의 주소가 다음과 같은 class로 정의되어 있다고 하자.
//편의상 getter/setter는 생략한다. public class Address { private String zipCode; private String address1; private String address2; }
public class User { ... private Address address; ... }
위와 같이 정의된 상태에서 주소가 서울인 사용자만을 조회한다고 하면 어떻게 해야 할까? findByAddressLike로 하면될까? 한번 해보시길.
그럼 위에서 사용한 custom interface를 제대로 사용해 보자. 현내용에 집중하기 위해 기존 메서드는 삭제하였다.
UserRepositoryCustom
public interface UserRepositoryCustom { Page<user> findByAddressLike(String partOfAddress, Pageable pageable); }
UserRepositoryImpl
public class UserRepositoryImpl implements UserRepositoryCustom { @Autowired MongoTemplate mongoTemplate; Page<user> findByAddressLike(String partOfAddress, Pageable pageable) { //like와 같은 효과를 내기 위해 정규식을 사용. Pattern addressPattern = Pattern.compile("^.*"+ partOfAddress + ".*"); Query query = new Query( Criteria.where("address.address1") .is(addressPattern) .or(address.address2) .is(addressPattern) ); } }
참조타입의 변수를 사용할 경우에는 위의 예제처럼 custom interface를 사용해서 데이터를 조회하면 될 것이다.
Fixed How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds #dev #it #asnwer
Fixed How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds #dev #it #asnwer
How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds
I am trying to work with Spring Data and Neo4j. I started by trying to follow this guide linked to by the main site. In particular I based my pom.xml off of the Hello World example file. Here is a snip from my pom.xml for the plugin that is causing the issues…
How to: How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds
How to: How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds
How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds
I am trying to work with Spring Data and Neo4j. I started by trying to follow this guide linked to by the main site. In particular I based my pom.xml off of the Hello World example file. Here is a snip from my pom.xml for the plugin that is causing the issues…
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
Spring, Hibernate, Spring Data, Akka, Twitter Bootstrap, Apache Tiles, jQuery powered Maven Java Web Project Kickstarter Codebase
I am happy to upload my second project to GitHub to help people get started with Java Web App Development as quickly as possible. I am sharing this code with Apache License 2.0. Here is the URL for the same:
1) Commons-Deps: Dependencies declared as a single pom file to easily manage the project dependencies. It is upto personal choice of users to still continue have it this way or go with their own chosen method to manage dependencies in maven pom.
2) Commons: A lot of common code snippets are provided as part of commons jar module to help send mails using gmail, java mail, utf8 encoding, JCS cache managers, session managers, random string, etc.
3) Framework: This part of the code base includes JPA and Spring Data Entities, JPA and Spring Data Repositories, Services which are built using Java Generics to help provide the CRUD actions on these Entities when users build their own domain specific entities, repositories and services extending the ones provided here. It also contains, API and Web App Controllers providing basic functionality again for people interested in building their own Spring MVC controllers using these. Also, contained here are validators, exceptions, AOP based exception handlers.
4) Your Own Web App Code: This part of the code provides a bootstrapped web project with API and Web UI using the best practices I picked across time to do things using the third party frameworks, libraries I have chosen here. The API parts is configured to accept and generate both XML and JSON request and response formats. Akka is also configured here to present the method in which it can be used to offload activities from your Spring MVC controllers (Servlets). Here it is programmed to offload the task of sending emails.
This is the wrapper framework laid out to start building Spring based Web apps with Hibernate ORM layer or Spring Data ORM powered NoSQL and Spring MVC in Java programming language. The purpose of this project is to get you started quickly in Java web app development over a widely used and tested Java web development infrastructure.
This project provides sample hibernate entities, spring data entities, akka actors to offload mail sending like jobs, models, repositories, services and controllers classes. There are also many framework level classes to help handle exceptions and errors in the project you may start developing using this. The UI for the default simple web project bundled in this framework is built using Twiiter Bootstrap, Apache Tiles, jQuery, jQuery Validation, JSPs.
I can try my best to provide with as much detail as possible here, but the best way to understand all that is provided is by reading the code. Therefore, I also provided a sample web app project with functionality to register and login a user. All the code is presented in a package structure that can be renamed as per your own choice and requirements. Enjoy!
The frameworks strung together supporting multiple activities in this framework layer of code are - Maven Java 1.7 Spring 3.1.1 Hibernate 4+ Spring Data MongoDB Akka 1.3+ Apache Tiles 2+ Twitter Bootstrap 2+ Velocity for Mails BootSwatch jQuery