使用Spring Boot JPA存储库进行更新不会将值提交到db

时间:2019-03-04 11:23:23

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

我正在开发Spring Boot应用程序,并且在对实体进行更新操作期间遇到提交问题。

以下是场景-

  1. 我有一个票证,其票证的版本属性更新为值“ A”
  2. 如果票证的版本已更新,则版本实体中的关联版本记录也应更新。此更新用于更新分配给该版本的票证总数。
  3. 我能够看到票证上的更新操作成功。但是,当我更新版本实体中的票证数量时,尽管正在进行更新,但不会提交。

以下是相同的代码。

控制器代码

@CrossOrigin
    @RequestMapping(value = "/updateOne", method = RequestMethod.PUT)
    @Transactional
    public Issue updateIssue(@RequestParam String issueId, @RequestBody Map<String, String> customUpdateQuery) throws Exception {

        logger.info("Inside updateIssue() API :: Updating Issue ::: " + issueId);

        if(issueId == null) {
            logger.info("Issue Id information was not passed. Raising an error");
            throw new Exception("Mandatory Input parameter (IssueId) not passed to updateIssue() API");
        }

        logger.info("updateIssue() :: Logging input parameters passed for updated!");

        if(customUpdateQuery != null) {
            for(String key : customUpdateQuery.keySet()) {
                logger.info( " Key ::: (" + key + ") ==> value ::: (" + customUpdateQuery.get(key) + ")");
            }
        }

        int recordsUpdated = 0;

        try {

            recordsUpdated = issueService.updateIssuebyIssueId(issueId, customUpdateQuery);

        } catch(NoResultException e) {
            System.out.println("No records found");
            e.printStackTrace();
            throw new NoResultException();
        } catch(Exception e) {
            System.out.println("Exception encountered");
            e.printStackTrace();
            throw new Exception("Exception encountered in update");
        }

        logger.info("Leaving updateEpic() API");

        Issue updatedIssue = null;

        if(recordsUpdated > 0 ) {
            updatedIssue =  issueService.findIssueById(issueId); 
        }

        return updatedIssue;

    }

ServiceImplCode

@Service
public class IssueServiceImpl implements IssueService {

    @Autowired
    IssueRepository issueRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    IssueComponentService issueComponentService;

    @Autowired
    VersionRepository versionRepository; /* Used for updating the version records with appropriate counts */

    public static final Logger logger = LoggerFactory.getLogger(IssueServiceImpl.class);

    @Override
    @Transactional
    public int updateIssuebyIssueId(String issueId, Map<String, String> customUpdateQuery)
            throws NoResultException, Exception {

        logger.info(" Inside updateIssuebyIssueId() API in IssueServiceImpl ::: " + issueId);

        int columnsToUpdate = 0;

        boolean componentUpdated = false;
        boolean fixVersionUpdated = false;
        boolean issueStatusUpdated = false;

        IssueComponent componentOldValue;
        Version fixVersionOldValue;
        String issueStatusOldvalue;

        Map<String, String> keyToValueMap = new HashMap<String, String>();

        StringBuilder updateSqlQuery = new StringBuilder("update issue i set ");

        for(String key : customUpdateQuery.keySet()) {

            if(columnsToUpdate == 0) {

                updateSqlQuery = updateSqlQuery.append("i." + column).append(" = ?");
            } 
            else {

                updateSqlQuery = updateSqlQuery.append(", ");

                updateSqlQuery = updateSqlQuery.append("i." + column).append(" = ?");
            }

            columnsToUpdate++;          
        }

        updateSqlQuery.append(" where i.id = ?");

        logger.info("updateIssuebyIssueId() :: Update Query :: " + updateSqlQuery);

        Query query = entityManager.createNativeQuery(updateSqlQuery.toString());

        int index = 1;
        int recordsUpdated = 0;

        for(String key: customUpdateQuery.keySet()) {

            if(key.equalsIgnoreCase("id")) {
                continue;
            }

            if(customUpdateQuery.get(key) == "") {
                logger.info("Setting value to null for key :: " + key);
                query.setParameter(index, null);
            } else {
                query.setParameter(index, customUpdateQuery.get(key));
            }
            index++;
        }

        query.setParameter(index, issueId);

        if(componentUpdated || fixVersionUpdated || issueStatusUpdated) {

            logger.info("Fix version, Component (or) Status for the issue is updated ::: " + issueId);

            logger.info("*** Storing current fixVersion, affectsVersion, component (or) status value from database ***");

            Issue issueRec = issueRepository.findById(issueId);

            if(issueRec != null) {

                issueStatusOldvalue = issueRec.getStatus();

                componentOldValue = issueRec.getComponent();

                fixVersionOldValue = issueRec.getFixVersion();


                if(componentUpdated && componentOldValue != null) {

                    logger.info("Component of Issue before update ::: " + componentOldValue.getId());
                } else {
                    logger.info("Component of Issue before update ::: NULL ");
                }

                if(fixVersionUpdated && fixVersionOldValue != null) {

                    logger.info("Version of Issue before update ::: " + fixVersionOldValue.getId());
                }else {
                    logger.info("Version of Issue before update ::: NULL ");
                }

                if(issueStatusUpdated) {

                    logger.info("Status of Issue before update ::: " + issueStatusOldvalue);
                }

                if(fixVersionUpdated && !issueStatusUpdated) {

                    keyToValueMap.put("fixVersionOldValue", (fixVersionOldValue == null)? null: fixVersionOldValue.getId() );
                    keyToValueMap.put("fixVersionNewValue", (customUpdateQuery.get("fixVersion") == "" || customUpdateQuery.get("fixVersion") == null) ? null: customUpdateQuery.get("fixVersion"));
                    keyToValueMap.put("issueStatusOldvalue", issueStatusOldvalue);
                }

                if(issueStatusUpdated && !fixVersionUpdated) {
                    keyToValueMap.put("fixVersionOldValue", (fixVersionOldValue == null)? null: fixVersionOldValue.getId());
                    keyToValueMap.put("issueStatusOldvalue", issueStatusOldvalue);
                    keyToValueMap.put("issueStatusNewValue", customUpdateQuery.get("status"));
                }

                if(fixVersionUpdated && issueStatusUpdated) {
                    keyToValueMap.put("fixVersionOldValue", (fixVersionOldValue == null)? null: fixVersionOldValue.getId() );
                    keyToValueMap.put("fixVersionNewValue", (customUpdateQuery.get("fixVersion") == "" || customUpdateQuery.get("fixVersion") == null) ? null: customUpdateQuery.get("fixVersion"));
                    keyToValueMap.put("issueStatusOldvalue", issueStatusOldvalue);
                    keyToValueMap.put("issueStatusNewValue", customUpdateQuery.get("status"));
                }

                if(componentUpdated) {

                    if(componentOldValue == null) {
                        keyToValueMap.put("componentOldValue", null);
                    } else {
                        keyToValueMap.put("componentOldValue", componentOldValue.getId());
                    }

                    if(customUpdateQuery.get("component") == "") {
                        keyToValueMap.put("componentNewValue", null);
                    } else {
                        keyToValueMap.put("componentNewValue", customUpdateQuery.get("component"));
                    }

                }
            }
        }


        logger.info("updateIssuebyIssueId() :: Final Update Query with values :: " + updateSqlQuery);

        try {

            logger.info("************************** updateIssuebyIssueId() :: Saving updates *************************");

            entityManager.joinTransaction();

            recordsUpdated = query.executeUpdate();

            logger.info("************************** updateIssuebyIssueId() :: Saved updates *************************");

        } catch(NoResultException e) {
            System.out.println("No records found");
            e.printStackTrace();
            throw new NoResultException();
        }catch (Exception e) {
            System.out.println("Exception encountered");
            e.printStackTrace();
            throw new Exception("Exception encountered");
        }

        try {

            logger.info("************************** updateIssuebyIssueId() :: Updating Relation count values *************************");               

            updateIssueRelationalComponentCounts(issueId, keyToValueMap, componentUpdated, fixVersionUpdated, issueStatusUpdated); 

            logger.info("************************** updateIssuebyIssueId() :: Updated Relation count values *************************");

        } catch(NoResultException e) {
            System.out.println("No records found");
            e.printStackTrace();
            throw new NoResultException();
        }catch (Exception e) {
            System.out.println("Exception encountered");
            e.printStackTrace();
            throw new Exception("Exception encountered");
        }

        /* clear the cache to return the updated data */
        entityManager.clear();

        return recordsUpdated;

    }


    private void updateIssueRelationalComponentCounts(String issueId, Map<String, String> keyToValueMap, 
                    boolean componentUpdated, boolean fixVersionUpdated, boolean statusUpdated) throws NoResultException, Exception {

        logger.info(" Inside updateIssueRelationalComponentCounts() API in IssueServiceImpl ::: " + issueId);

        if(keyToValueMap == null || keyToValueMap.size() <= 0) {
            return;
        }

        if(fixVersionUpdated) {

            logger.info(" Inside updateIssueRelationalComponentCounts() API ::: Either fixVersion (or) status (or) both are Updated ");

            logger.info(" Inside updateIssueRelationalComponentCounts() API ::: Only fixVersion is Updated ");

            String fixVersionOldValue = keyToValueMap.get("fixVersionOldValue");

            String fixVersionNewValue = keyToValueMap.get("fixVersionNewValue");

            logger.info("Fix Version changed from " + ((fixVersionOldValue == null) ? "Null": fixVersionOldValue) + " ==> " + fixVersionNewValue);

            Version newVersionRec = versionRepository.findById(fixVersionNewValue);

            Integer numOfIssuesAssigned = newVersionRec.getTotalIssues();
            Integer numOfIssuesToDo = newVersionRec.getIssuesToDo();
            Integer numOfIssuesInProgress = newVersionRec.getIssuesInProgress();
            Integer numOfIssuesCompleted = newVersionRec.getIssuesCompleted();
            Integer percentageCompleted = newVersionRec.getProgressPercentage();

            String status = keyToValueMap.get("issueStatusOldvalue");

            logger.info("Inside updateIssueRelationalComponentCounts() API ::: Printing Fix Version (" + fixVersionNewValue + ") DB Count");
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: DB numOfIssuesAssigned ::: " + numOfIssuesAssigned);
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: DB numOfIssuesToDo ::: " + numOfIssuesToDo);
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: DB numOfIssuesInProgress ::: " + numOfIssuesInProgress);
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: DB numOfIssuesCompleted ::: " + numOfIssuesCompleted);
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: DB percentageCompleted ::: " + percentageCompleted);
            logger.info("Inside updateIssueRelationalComponentCounts() API ::: Issue status ::: " + status);

            if(ApplicationConstants.Open.equalsIgnoreCase(status)) {
                numOfIssuesToDo = numOfIssuesToDo + 1;
            }

            if(ApplicationConstants.InProgress.equalsIgnoreCase(status) || ApplicationConstants.Resolved.equalsIgnoreCase(status)) {
                numOfIssuesInProgress = numOfIssuesInProgress + 1;
            }

            if(ApplicationConstants.Closed.equalsIgnoreCase(status)) {
                numOfIssuesCompleted = numOfIssuesCompleted + 1;
            }

            numOfIssuesAssigned = numOfIssuesAssigned + 1;
            float percentageCompletedfl = (numOfIssuesCompleted)/(numOfIssuesAssigned);
            percentageCompleted = Math.round(percentageCompletedfl);

            newVersionRec.setIssuesToDo(numOfIssuesToDo);
            newVersionRec.setIssuesInProgress(numOfIssuesInProgress);
            newVersionRec.setIssuesCompleted(numOfIssuesCompleted);
            newVersionRec.setTotalIssues(numOfIssuesAssigned);
            newVersionRec.setProgressPercentage(percentageCompleted);

            logger.info("updateIssueRelationalComponentCounts() :: Bind Params => (total_Issues) :: " + numOfIssuesAssigned + " (numOfIssuesToDo) ::  " + numOfIssuesToDo + " (numOfIssuesInProgress) ::  " + numOfIssuesInProgress +  " (numOfIssuesCompleted) ::  " + numOfIssuesCompleted + " (percentageCompleted) ::  " + percentageCompleted);

            logger.info("updateIssueRelationalComponentCounts() :: updating Version :: " + fixVersionNewValue);

            try {

                logger.info("******* updateIssueRelationalComponentCounts() :: Updating new Version count values *******");

                Version updateVersionRec = versionRepository.save(newVersionRec);

                logger.info("*** updateIssueRelationalComponentCounts() :: Updated new Version count values");

                logger.info("****** Printing updated Version value ******");

                logger.info("Version Id :::: " + updateVersionRec.getId());
                logger.info("Version Total Number of Assigned :::: " + updateVersionRec.getTotalIssues());
                logger.info("Version Total Number of Open :::: " + updateVersionRec.getIssuesToDo());
                logger.info("Version Total Number of In Progress :::: " + updateVersionRec.getIssuesInProgress());
                logger.info("Version Total Number of Closed :::: " + updateVersionRec.getIssuesCompleted());
                logger.info("Version Percentage Issues completed :::: " + updateVersionRec.getProgressPercentage());

            }catch(NoResultException e) {
                System.out.println("No records found");
                e.printStackTrace();
                throw new NoResultException();
            }catch (Exception e) {
                System.out.println("Exception encountered");
                e.printStackTrace();
                throw new Exception("Exception encountered");
            }  

        }

        logger.info(" Leaving updateIssueRelationalComponentCounts() API in IssueServiceImpl ::: " + issueId);
    }

updateIssueRelationalComponentCounts()方法负责更新Version实体中的计数。

我在versionRepository.save()操作之后立即打印了日志,并且该版本确实指示正在更新。

但是,当我从前端检查数据库时,我看不到提交的更新。

我需要手动提交吗?

我已经使用@Transactional注释了该方法,并假定该提交将自动发生。

我在这里想念什么?

很抱歉,粘贴的代码太长。

ServieImpl中的代码摘要。

  1. 方法updateIssuebyIssueId()首先更新主实体票证。
  2. 在此方法中,我们通过名称updateIssueRelationalComponentCounts()调用了一个方法
  3. 在调用上述方法之前,我需要捕获版本的DB和updateValues,以便可以正确设置计数,因此我们看到了很多逻辑来在Map中捕获此数据。
  4. 在方法-> updateIssueRelationalComponentCounts()中,我使用versionRepository-> save()方法相应地更新计数。

0 个答案:

没有答案