-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMappingPOJO.java
More file actions
44 lines (35 loc) · 1.43 KB
/
MappingPOJO.java
File metadata and controls
44 lines (35 loc) · 1.43 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.mongodb.quickstart;
import com.mongodb.quickstart.models.Grade;
import com.mongodb.quickstart.models.Score;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class MappingPOJO{
@Autowired
private StudentRepository repository;
public void run() {
// Create a new grade
Grade newGrade = new Grade()
.setId(new ObjectId())
.setStudentId(10003d)
.setClassId(10d)
.setScores(List.of(new Score().setType("homework").setScore(50d)));
repository.save(newGrade);
System.out.println("Grade inserted: " + newGrade);
// Find this grade
Grade grade = repository.findFirstByStudentId(10003d);
System.out.println("Grade found: " + (grade != null ? grade : "No data found"));
// Update this grade by adding an exam grade
List<Score> newScores = new ArrayList<>(grade.getScores());
newScores.add(new Score().setType("exam").setScore(42d));
grade.setScores(newScores);
Grade updatedGrade = repository.save(grade);
System.out.println("Grade updated: " + updatedGrade);
// Delete this grade
repository.deleteById(updatedGrade.getId().toString());
System.out.println("Grade deleted.");
}
}