|
| 1 | +package coursepick.coursepick.infrastructure; |
| 2 | + |
| 3 | +import coursepick.coursepick.domain.*; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import org.springframework.data.geo.Point; |
| 6 | +import org.springframework.data.mongodb.core.MongoTemplate; |
| 7 | +import org.springframework.data.mongodb.core.geo.GeoJsonPoint; |
| 8 | +import org.springframework.data.mongodb.core.query.Criteria; |
| 9 | +import org.springframework.data.mongodb.core.query.Query; |
| 10 | +import org.springframework.stereotype.Repository; |
| 11 | + |
| 12 | +import java.util.List; |
| 13 | +import java.util.Optional; |
| 14 | +import java.util.stream.StreamSupport; |
| 15 | + |
| 16 | +@Repository |
| 17 | +@RequiredArgsConstructor |
| 18 | +public class CourseRepositoryMongoTemplateImpl implements CourseRepository { |
| 19 | + |
| 20 | + private final MongoTemplate mongoTemplate; |
| 21 | + |
| 22 | + @Override |
| 23 | + public void saveAll(Iterable<? extends Course> courses) { |
| 24 | + /* |
| 25 | + 배치 삽입을 통해 성능을 높일 수 있다. 단, 현재 새벽2시에만 호출되는 메서드라, 크게 필요해보이지는 않는다. |
| 26 | + 또한, 현재 메모리 문제가 더 크므로 일단은 넘긴다. 필요한 경우 아래 코드를 참고할 것 |
| 27 | + BulkOperations ops = mongoTemplate.bulkOps(BulkMode.UNORDERED, Course.class); |
| 28 | + ops.insert(courses); |
| 29 | + ops.execute(); |
| 30 | + */ |
| 31 | + List<? extends Course> listCourses = StreamSupport.stream(courses.spliterator(), false) |
| 32 | + .toList(); |
| 33 | + mongoTemplate.insertAll(listCourses); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public List<Course> findAllHasDistanceWithin(Coordinate target, Meter distance) { |
| 38 | + if (target == null || distance == null) return List.of(); |
| 39 | + |
| 40 | + Point center = new GeoJsonPoint(target.longitude(), target.latitude()); |
| 41 | + Query query = Query.query(Criteria.where("segments").near(center).maxDistance(distance.value())); |
| 42 | + return mongoTemplate.find(query, Course.class); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public List<Course> findByIdIn(List<String> ids) { |
| 47 | + if (ids == null || ids.isEmpty()) return List.of(); |
| 48 | + |
| 49 | + Query query = Query.query(Criteria.where("_id").in(ids)); |
| 50 | + return mongoTemplate.find(query, Course.class); |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public Optional<Course> findById(String id) { |
| 55 | + if (id == null) return Optional.empty(); |
| 56 | + |
| 57 | + return Optional.ofNullable(mongoTemplate.findById(id, Course.class)); |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public boolean existsByName(CourseName courseName) { |
| 62 | + if (courseName == null) return false; |
| 63 | + |
| 64 | + Query query = Query.query(Criteria.where("name").is(courseName.value())); |
| 65 | + return mongoTemplate.exists(query, Course.class); |
| 66 | + } |
| 67 | +} |
0 commit comments