Sprint Boot JPA不会使用保存方法

时间:2016-02-09 17:40:16

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

我是Spring Boot和JPA的新手,我正在尝试更新mysql数据库中的记录。在我的控制器下面,我能够成功地将新记录保存到数据库中并查找现有记录。但是,当我尝试更新现有记录时,没有任何反应。 (如同,它不会保存并跳过该方法。)

以下是我的控制器。注意,errorUpdateService.fineErrorByName可以成功检索数据库中的现有记录。

@Autowired
private ErrorUpdateService errorUpdateService;


@RequestMapping(value="/api/UpdateError", method=RequestMethod.POST)
@ResponseBody
public String updateError(@RequestBody Error error){
    try{
        Error retrievedError=errorUpdateService.findErrorByName((error.getName()));
        if(!retrievedError.getName().equals("NVE")){
            System.out.println("Here is error: "+retrievedError.toString());
            errorUpdateService.updateError(retrievedError);
            return retrievedError.getName() + " has been updated";
        }
    }catch(NullPointerException e){
        errorUpdateService.updateError(error);
        return "Error Name Does not Exist.  Saving " +error.getName() ;
    }
    return "Failed Method";
}

当代码执行到errorUpdateService.updateError(retrievedError);时,它不会保存到数据库并且似乎跳过。但是,如果发送数据库中不存在的记录,则不会产生任何问题(请参阅Null Pointer catch块)。

请参阅下面的ErrorUpdateServiceImpl “

@Autowired
private ErrorRepository errorRepository;

@Override
public void updateError(Error error) {
    System.out.println("Attempting to save a error: "+error.toString());
    errorRepository.save(error);
}

@Override
public Error findErrorByName(String errName){

    try{
        Error error=errorRepository.findByErrName(errName);

        return error;
    }catch(NullPointerException e){
        return new Error("NVE");
    }   
}

public interface ErrorRepository extends JpaRepository<Error, Long>{

    Error findByErrName(String errName);
}

以下是尝试更新记录时的示例控制台输出:

Hibernate: select error0_.id as id1_0_, error0_.documentationurl as document2_0_, error0_.err_name as err_name3_0_, error0_.error_id as error_id4_0_, error0_.has_documentation as has_docu5_0_, error0_.last_incident_time as last_inc6_0_, error0_.throttle_minutes as throttle7_0_, error0_.throttle_threshold as throttle8_0_ from error error0_ where error0_.err_name=?
Here is error: Error [id=6, errorId=0, hasDocumentation=false, errName=Error0001, documentationURL=null, throttleThreshold=0, throttleMinutes=0, lastIncidentTime=null]
Attempting to save a error: Error [id=6, errorId=0, hasDocumentation=false, errName=Error0001, documentationURL=null, throttleThreshold=0, throttleMinutes=0, lastIncidentTime=null]

1 个答案:

答案 0 :(得分:1)

我是否遗漏了某些内容,或者您​​正在尝试使用您检索的相同记录更新记录?您正在使用完全相同的值更新它,所以也许这就是您没有看到任何更改的原因?