5 Kasım 2018 Pazartesi

SpringData MongoDB MongoRepository Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.data.mongodb.repository.MongoRepository;
@Document olarak işaretli sınıflara erişimi sağlar. Eğer Spring'in ürettiği kod yetersiz ise MongoTemplate kullanılabilir.

ID Parametresi
İkinci parametre ID tipinin ne olduğunu belirtir. Spring bazı Java tiplerini MongoDB'nin ObjectId tipine çevirebilir. Açıklaması şöyle.
An id property or field declared as a String in the Java class will be converted to and stored as an ObjectId if possible using a Spring Converter. Valid conversion rules are delegated to the MongoDB Java driver. If it cannot be converted to an ObjectId, then the value will be stored as a string in the database.
An id property or field declared as BigInteger in the Java class will be converted to and stored as an ObjectId using a Spring Converter.
ObjectId yapısı şöyle
0   1   2   3   4   5   6   7   8   9   10  11

|time          |machine    |pid    |inc      |
Yeni ObjectId yaratmak için şöyle yaparız.
ObjectId id1 = new ObjectId(); //Generates unique id 
ObjectId id2 = ObjectId.get(); //Calls new ObjectId();
Dolayısıyla String ve BigInteger dışındakiler çalışmıyor. Şu kod Long kullandığı için exception fırlatır.
public interface FooRepository extends Mongoepository<Foo, Long> {
  ...
}
Maven
Şöyle yaparız.
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
deleteAll metodu
Örnek ver

find metodu
Şöyle yaparız.
@Override
public List<Device> findByMapKey(String mapKey,String value, Class clazz) {

  Query query = Query.query(Criteria.where("basicInfo."+mapId).is(value));

  return mongoTemplate.find(query,clazz);
}
findAll metodu
Örnek
Şöyle yaparız
@RequestMapping(method=RequestMethod.GET,value="/movie")
public ResponseEntity getAllMovies()
{
  List<Movie> movies=movieRepo.findAll();
  if(movies.size()>0){
    return new ResponseEntity(movies,HttpStatus.OK);
  }
  else {
    return new ResponseEntity("No movies found",HttpStatus.NOT_FOUND);
  }
}
deleteByXXX metodu
Örnek
Şöyle yaparız
@RequestMapping(method=RequestMethod.DELETE,value="/movie/{id}")
public ResponseEntity deleteMovieById(@PathVariable("id") String id)
{
  try{
    movieRepo.deleteById(id);
    return new ResponseEntity("Successfully deleted movie with id "+id,HttpStatus.OK);
  } catch (Exception e) {
    return new ResponseEntity(e.getMessage(),HttpStatus.NOT_FOUND);
  }
}
Örnek - custom metod
Şöyle yaparız.
public interface AuditProjectRepository extends MongoRepository<BaseQuestion, String> {

  public Long deleteByQuestionId(int questionid);
  ...
}
findByXXX metodu
find metodları altta MongoTemplate sınıfını kullanır.

Örnek
Şöyle yaparız.
/* BookData.java */
@Document
public class BookData {

  @Id private String id;
  // Some more non-Id Strings...
  private Config config;
  private Metadata metadata;
  private Boolean downloaded;
  private Integer currentPageNumber;
  private int availablePages;
  private List<Bookmark> bookmarks;
  private StatsModel stats;

  @Transient private byte[] contents;

  public BookData() {}

  // getters and setters
}

/* BookDataRepository.java */
// MongoRepository comes from spring-boot-starter-parent-1.4.5.RELEASE
public interface BookDataRepository extends MongoRepository<BookData, String> {
  BookData findById(String id);
}
Örnek
Şöyle yaparız.
@Query(value = "{'address.country':?0}")
public List<Hotel> findByCountry(String country);
save metodu
Metodun içi şöyledir
@Override
public <S extends T> S save(S entity) {

  Assert.notNull(entity, "Entity must not be null!");

  if (entityInformation.isNew(entity)) {
    return mongoOperations.insert(entity, entityInformation.getCollectionName());
  }

  return mongoOperations.save(entity, entityInformation.getCollectionName());
}
Örnek
Elimizde şöyle bir kod olsun. Bu koddaki Movie nesnesi @Document ve @Id ile işaretli
public interface MovieRepository extends MongoRepository<Movie,String> {}
Şöyle yaparız
@RequestMapping(method= RequestMethod.POST,value="/movie")
public ResponseEntity<String> createMovie(@RequestBody Movie movie)
{
  try{
    movieRepo.save(movie);
    return new ResponseEntity("Successfully added movie "+movie.getTitle(), HttpStatus.OK);
  }
  catch(Exception e){
    return new ResponseEntity(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
Örnek
Şöyle yaparız
@RequestMapping(method=RequestMethod.PUT,value="/movie/{id}")
public ResponseEntity updateById(@PathVariable("id") String id,@RequestBody Movie newMovie)
{
  Optional<Movie> movieOptional =movieRepo.findById(id);
  if(movieOptional.isPresent()) {
    Movie movieToSave=movieOptional.get();
    movieToSave.setTitle(newMovie.getTitle());
    movieToSave.setRating(newMovie.getRating());
    movieToSave.setGenre(newMovie.getGenre());
    movieRepo.save(movieToSave);
    return new ResponseEntity("Updated Movie with id "+id,HttpStatus.OK);
  } else {
    return new ResponseEntity("No Movie with id "+id+" found",HttpStatus.NOT_FOUND);
  }
}
findByLocationNear metodu
Örnek
Şöyle yaparız
public interface UserRepository extends MongoRepository<User, String> {} public interface PlaceRepository extends MongoRepository<Place, String> {} @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> findNearbyFriends(String userId, Distance distance) { User user = userRepository.findById(userId) .orElseThrow(() -> new RuntimeException("User not found")); Point userLocation = new Point(user.getLocation().getX(), user.getLocation().getY()); return userRepository.findByLocationNear(userLocation, distance); } } @Service public class PlaceService { @Autowired private PlaceRepository placeRepository; public List<Place> findNearbyPlaces(String userId, Distance distance) { User user = userRepository.findById(userId) .orElseThrow(() -> new RuntimeException("User not found")); Point userLocation = new Point(user.getLocation().getX(), user.getLocation().getY()); return placeRepository.findByLocationNear(userLocation, distance); } }




Hiç yorum yok:

Yorum Gönder