问题
I have the following Spring boot
service for an object of type Report
-
@Service
public class ReportService {
@Autowired
private ReportRepository reportRepository;
@Autowired
private UserRepository userRepository;
/*get all reports */
public List<Report> getAllReports(){
return reportRepository.findAll();
}
/*get a single report */
public Report getReport(Long id){
return reportRepository.getOne(id);
}
//other similar methods....
}
The problem arises while retrieving a single Report. If a report ID is send which doesn't exist, the following error is generated...
DefaultHandlerExceptionResolver : Failed to write HTTP message:
org.springframework.http.converter.HttpMessageNotWritableException: Could not
write JSON: Unable to find com.interact.restapis.model.Report with id 16;
nested exception is com.fasterxml.jackson.databind.JsonMappingException:
Unable to find com.interact.restapis.model.Report with id 16 (through
reference chain:
com.interact.restapis.model.Report_$$_jvst83c_1["fromUserId"])
Below is the code for my Report Controller
@RestController
public class ReportController {
@Autowired
private ReportService reportService;
//Get all reports
@GetMapping("/interactions")
public List<Report> getAllReports() {
return reportService.getAllReports();
}
//Get single report
@GetMapping("/interactions/{id}")
public ResponseEntity<Report> getReport(@PathVariable Long id) {
if(reportService.getReport(id) == null)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(reportService.getReport(id), HttpStatus.OK);
}
@PostMapping("/interactions")
public ResponseEntity<Report> addReport(@RequestBody Report report) {
Report report1 = reportService.addReport(report);
if(report1 == null)
return new ResponseEntity<>(report, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(report1, HttpStatus.OK);
}
//Other request methods...
}
Below is the code for my Report Model class -
@Entity
@Table (name = "report")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Report {
@Id
@Column (name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "from_user_id")
private Long fromUserId;
@Column(name = "to_user_id")
private Long toUserId;
@Column(name = "to_user_email")
private String toUserEmail;
@Column(name = "from_user_email")
private String fromUserEmail;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
@CreatedDate
private Date createdAt;
@Column(nullable = false)
private String observation;
@Column(nullable = false)
private String context;
private String recommendation;
@Column(nullable = false)
private String eventName;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
@Column(nullable = false)
private Date eventDate;
private boolean isAnonymous;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
private Date acknowledgementDate;
@OneToMany(cascade = CascadeType.ALL, targetEntity = Action.class)
@JoinColumn(name = "report_id")
private List<Action> actionList;
@Value("${some.key:0}")
private int rating; //Range 0 to 4
private int type;
/*
Getter and setter methods...
*/
}
I want to know if reportRepository.getOne(Long id)
returns null so that I can actually check if a particular report doesn't exist in the database. If not, how else can I implement the above?
回答1:
The JpaRepository.getOne
with throw EntityNotFoundException
if it couldn't find a record with the given id.
You can use CrudRepository.findById
(JpaRepository
is a subclass of CrudRepository
) which will return an Optional<Report>
which can be empty if there are no record for the given id. You can use Optional.isPresent()
to check whether it a Report
is available or not and take actions accordingly.
回答2:
Create a method in your ReportRepository
.
It will return Report by matched id else return null.
public Optional<Report> findById(Long id);
Note: findById(Long id); should match with the property name in your Report
entity.
I am assuming your Report entity is as follows:
public class Entity{
private Long id;
...
}
来源:https://stackoverflow.com/questions/51758941/return-type-of-jpa-repository-getoneid-method