0

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?

4

2 回答 2

2

如果找不到具有给定 id 的记录,则抛出JpaRepository.getOneEntityNotFoundException

您可以使用CrudRepository.findById( JpaRepositoryis a subclass of )如果给定 id 没有记录CrudRepository,它将返回一个可以为空的。Optional<Report>您可以使用Optional.isPresent()它来检查它Report是否可用并采取相应的措施。

于 2018-08-09T04:52:07.273 回答
1

在您的ReportRepository. 它将通过匹配的 id 返回报告,否则返回 null。

public Optional<Report>  findById(Long id);

注:findBy Id(长id);应与您的Report 实体中的属性名称匹配。

我假设您的报告实体如下:

public class Entity{
private Long id;
...
}
于 2018-08-09T04:55:13.677 回答