JPA存储库“ getOne(id)”方法的返回类型

时间:2018-08-09 04:37:34

标签: spring spring-boot spring-data-jpa spring-repositories

我为类型Spring boot-

的对象提供以下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....
    }

在检索单个报告时出现问题。如果发送的报告ID不存在,则会生成以下错误...

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"])

下面是我的报告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...
}

下面是我的报表模型类的代码-

@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...
     */
}

我想知道reportRepository.getOne(Long id)是否返回null,以便实际上可以检查数据库中是否不存在特定的报告。如果没有,我还能如何实现上述目标?

2 个答案:

答案 0 :(得分:2)

如果找不到指定ID的记录,则抛出JpaRepository.getOne的{​​{1}}。

您可以使用EntityNotFoundExceptionCrudRepository.findByIdJpaRepository的子类),它将返回CrudRepository,如果没有给定ID的记录,则可以为空。您可以使用Optional<Report>来检查Optional.isPresent()是否可用,并采取相应的措施。

答案 1 :(得分:1)

在您的ReportRepository中创建一个方法。 它将通过匹配的ID返回报告,否则返回null。

public Optional<Report>  findById(Long id);

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

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

public class Entity{
private Long id;
...
}