當前位置: 首頁>>代碼示例>>Java>>正文


Java DuplicateKeyException類代碼示例

本文整理匯總了Java中org.springframework.dao.DuplicateKeyException的典型用法代碼示例。如果您正苦於以下問題:Java DuplicateKeyException類的具體用法?Java DuplicateKeyException怎麽用?Java DuplicateKeyException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DuplicateKeyException類屬於org.springframework.dao包,在下文中一共展示了DuplicateKeyException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: signUp

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@PostMapping(path = "signup")
public ResponseEntity<?> signUp(@RequestBody @Valid User user, HttpSession httpSession) {
    if (!checkUser(user)) {
        return TypicalResponses.BAD_REQUEST;
    }

    final Integer userId = (Integer) httpSession.getAttribute("user");
    if (userId != null) {
        User curUser = userService.getUser(userId);
        return ResponseEntity.badRequest().body(curUser); // Already authorized by curUser
    }
    try {
        user = userService.create(user);
    } catch (DuplicateKeyException e) {
        return TypicalResponses.USERNAME_ALREADY_USED_RESPONSE;
    }
    httpSession.setAttribute("user", user.getId());

    return ResponseEntity.ok(user);
}
 
開發者ID:java-park-mail-ru,項目名稱:SpaceInvasion-09-2017,代碼行數:21,代碼來源:UserController.java

示例2: add

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
 * @desc 新增鏈路
 *
 * @author liuliang
 *
 * @param linkBO 鏈路BO
 * @return Result
 */
@RequestMapping(value = "/add")
@ResponseBody
public Result add(@Validated(Groups.Add.class) LinkBO linkBO,BindingResult br){
    Result result = new Result();
    //參數校驗
    Result validateResult = ValidatorUtil.getValidResult(br);
    if(ResultUtil.isfail(validateResult)) {
        return ResultUtil.copy(validateResult, result);
    }
    //新增
    try {
        int addResult = linkService.addLink(linkBO);
        if(0 < addResult) {
            return ResultUtil.success(result);
        }
    } catch(DuplicateKeyException de){
        logger.error("新增數據異常,鏈路名重複,params:{}",linkBO.toString(),de);
        return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,"鏈路名已存在",result);
    } catch (Exception e) {
        logger.error("新增數據異常,params:{}",linkBO.toString(),e);
    }
    //返回失敗結果
    return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
 
開發者ID:yunjiweidian,項目名稱:TITAN,代碼行數:33,代碼來源:LinkController.java

示例3: updateResource

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
public void updateResource(AdminResource resource) {
    ValidationAssert.notNull(resource, "參數不能為空!");
    ValidationAssert.notNull(resource.getResourceId(), "資源id不能為空!");
    resource.setPermissionExpression(StringUtils.defaultIfEmpty(resource.getPermissionExpression(), null));
    resource.setResourceUrl(StringUtils.defaultIfEmpty(resource.getResourceUrl(), null));
    AdminResource presource = adminResourceMapper.selectThinResourceById(resource.getResourceId(), true);
    ValidationAssert.notNull(presource, "該資源已經不存在了!");
    try {
        adminResourceMapper.updateResource(resource);
    } catch(DuplicateKeyException e) {
        BusinessAssert.isTrue(!e.getCause().getMessage().toUpperCase().contains("RESOURCE_NAME"), "修改資源失敗,該資源名稱已經存在!");
        BusinessAssert.isTrue(!e.getCause().getMessage().toUpperCase().contains("PERMISSION_EXPRESSION"), "修改資源失敗,該權限表達式已經存在!");
        throw e;
    }
}
 
開發者ID:penggle,項目名稱:xproject,代碼行數:17,代碼來源:AdminResourceServiceImpl.java

示例4: insertSources

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
 * Insert sources into database after server startup.
 */
@PostConstruct
public void insertSources() {
    List<Source> sources = new ArrayList<>();
    sources.add(new Source("the-next-web", "The Next Web", "latest"));
    sources.add(new Source("associated-press", "Associated Press", "latest"));
    sources.add(new Source("bbc-news", "BBC News", "top"));
    sources.add(new Source("bloomberg", "Bloomberg", "top"));
    sources.add(new Source("business-insider", "Business Insider", "latest"));
    sources.add(new Source("buzzfeed", "BuzzFeed", "latest"));
    sources.add(new Source("cnbc", "CNBC", "top"));
    sources.add(new Source("cnn", "CNN", "top"));
    sources.add(new Source("entertainment-weekly", "Entertainment Weekly", "top"));
    sources.add(new Source("financial-times", "Financial Times", "latest"));
    for (Source s : sources) {
        try {
            sourceRepository.save(s);
            logger.info(s.getName() + " added as source.");
        } catch (DuplicateKeyException ex) {
            logger.warn(s.getName() + " already in database, not inserted");
        }
    }

}
 
開發者ID:BakkerTom,項目名稱:happy-news,代碼行數:27,代碼來源:NewsCrawler.java

示例5: createValue

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
 * Simulate creation of a new database entry
 */
public Pair<Long, Object> createValue(Object value)
{
    assertTrue(value == null || value instanceof TestValue);
    String dbValue = (value == null) ? null : ((TestValue)value).val;
    
    // Kick out any duplicate values
    if (database.containsValue(dbValue))
    {
        throw new DuplicateKeyException("Value is duplicated: " + value);
    }
    
    // Get the last key
    Long lastKey = database.isEmpty() ? null : database.lastKey();
    Long newKey = null;
    if (lastKey == null)
    {
        newKey = new Long(1);
    }
    else
    {
        newKey = new Long(lastKey.longValue() + 1);
    }
    database.put(newKey, dbValue);
    return new Pair<Long, Object>(newKey, value);
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:29,代碼來源:EntityLookupCacheTest.java

示例6: saveConnection

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@Override
public void saveConnection(ConnectionInfo connectionInfo) throws DataExistException {
    try{
        if(connectionInfo.getId()!=null){
            connectionInfo.setUpdatedDate(new Date());
            connectionInfoMapper.updateByPrimaryKeySelective(connectionInfo);
        }else{
            connectionInfo.setCreatedDate(new Date());
            connectionInfo.setUpdatedDate(new Date());
            connectionInfoMapper.insert(connectionInfo);
        }
    }catch (DuplicateKeyException dke){
        throw new DataExistException("已經存在:["+connectionInfo.getConnectUrl()+"]的連接信息");
    }

}
 
開發者ID:liaojiacan,項目名稱:zkAdmin,代碼行數:17,代碼來源:CoreServiceImpl.java

示例7: add

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
 * Add a new ValueDescriptor whose name must be unique. ServcieException (HTTP 503) for unknown or
 * unanticipated issues. DataValidationException (HTTP 409) if the a formatting string of the
 * value descriptor is not a valid printf format or if the name is determined to not be unique
 * with regard to other value descriptors.
 * 
 * @param valueDescriptor object
 * @return id of the new ValueDescriptor
 * @throws ServcieException (HTTP 503) for unknown or unanticipated issues
 * @throws DataValidationException (HTTP 409) if the format string is not valid or name not unique
 */
@RequestMapping(method = RequestMethod.POST)
@Override
public String add(@RequestBody ValueDescriptor valueDescriptor) {
  if (!validateFormatString(valueDescriptor))
    throw new DataValidationException(
        "Value descriptor's format string doesn't fit the required pattern: " + formatSpecifier);
  try {
    valDescRepos.save(valueDescriptor);
    return valueDescriptor.getId();
  } catch (DuplicateKeyException dE) {
    throw new DataValidationException(
        "Value descriptor's name is not unique: " + valueDescriptor.getName());
  } catch (Exception e) {
    logger.error("Error adding value descriptor:  " + e.getMessage());
    throw new ServiceException(e);
  }
}
 
開發者ID:edgexfoundry,項目名稱:core-data,代碼行數:29,代碼來源:ValueDescriptorControllerImpl.java

示例8: createCIRelation

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@RequestMapping(method=RequestMethod.POST, value="/cm/simple/relations")
@ResponseBody
public CmsCIRelationSimple createCIRelation(
        @RequestParam(value="value", required = false)  String valueType, 
        @RequestBody CmsCIRelationSimple relSimple,
        @RequestHeader(value="X-Cms-Scope", required = false)  String scope,
        @RequestHeader(value="X-Cms-User", required = false)  String userId) throws CIValidationException {
    
    scopeVerifier.verifyScope(scope, relSimple);
    
    CmsCIRelation rel = cmsUtil.custCIRelationSimple2CIRelation(relSimple, valueType);
    rel.setCreatedBy(userId);
    try {
        CmsCIRelation newRel = cmManager.createRelation(rel);
        return cmsUtil.custCIRelation2CIRelationSimple(newRel, valueType,false);
    } catch (DataIntegrityViolationException dive) {
        if (dive instanceof DuplicateKeyException) {
            throw new CIValidationException(CmsError.CMS_DUPCI_NAME_ERROR, dive.getMessage());
        } else {
            throw new CmsException(CmsError.CMS_EXCEPTION, dive.getMessage());
        }
    }
}
 
開發者ID:oneops,項目名稱:oneops,代碼行數:24,代碼來源:CmRestController.java

示例9: addTaskDependency

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@Override
public int addTaskDependency(List<TaskDependencyEntity> list, String groupId) {
    // 刪除任務組內所有的連線信息
    jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_218"), groupId);

    for (TaskDependencyEntity m : list) {
        try {
            if (1 != jdbcTemplate.update(batchSqlText.getSql("sys_rdbms_151"),
                    DigestUtils.sha1Hex(JoinCode.join(m.getJobKey(), m.getUpJobKey())),
                    m.getJobKey(),
                    m.getUpJobKey(),
                    m.getDomainId())) {
                logger.warn("新增任務失敗");
                return -1;
            }
        } catch (DuplicateKeyException e) {
            logger.warn("任務已經存在,刷新成功,{}", m.getJobKey());
        }
    }
    return 1;
}
 
開發者ID:hzwy23,項目名稱:batch-scheduler,代碼行數:22,代碼來源:GroupTaskDaoImpl.java

示例10: createChannel

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
 * Create channel with unique name.
 *
 * @param name channel name.
 * @return created channel.
 */
public Channel createChannel(String name) {
    if (StringUtils.isBlank(name)) {
        throw new ChatException("Channel name must not be null", HttpStatus.BAD_REQUEST);
    }

    name = name.trim();
    try {
        LOGGER.debug("Creating new channel with name: {}", name);
        return channelRepository.save(new Channel(name));

    } catch (DuplicateKeyException e) {
        LOGGER.error("Could not channel: {}",
                e.getMostSpecificCause().getMessage());

        throw new ChatException("Channel with such name already exists", HttpStatus.BAD_REQUEST);
    }
}
 
開發者ID:Edvinas01,項目名稱:chat-rooms,代碼行數:24,代碼來源:ChannelService.java

示例11: createBooking

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
public Event createBooking(Event event, User user, String comment) throws Exception {
    Booking booking = new Booking();
    booking.setComment(comment);
    booking.setUser(user);
    boolean find = false;
    List<Booking> books = event.getBooking();

    for (Booking book : books) {
        if(book.getUser().getUsername().equals(user.getUsername())){
            find = true;
            break;
        }
    }

    if(find)throw new DuplicateKeyException("this account already exists");

    books.add(booking);
    event.setBooking(books);
    return eventRepository.save(event);
}
 
開發者ID:stasbranger,項目名稱:RotaryLive,代碼行數:21,代碼來源:EventServiceImpl.java

示例12: addGateRoute

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
/**
* @title: addGateRoute
* @description: 渠道新增
* @author li.zhenxing
* @date 2014-11-10
* @param gid
* @param name
* @param merNo
* @param requestUrl
* @param remark
*/ 
public String addGateRoute(Integer gid,String name,String merNo,String requestUrl,String remark){
    String msg = "添加失敗";
    try {
        if(null != gid && StringUtils.isNotBlank(name) && StringUtils.isNotBlank(merNo) && StringUtils.isNotBlank(requestUrl) && StringUtils.isNotBlank(remark)){
            int count  = dao.addGateRoute(gid, name, merNo, requestUrl, remark);
            dao.saveOperLog("支付渠道維護", "gid:"+gid+",name:"+name+",merNo:"+merNo+",requestUrl:"+requestUrl+",remark:"+remark);
            if(count == 1){
                msg = AppParam.SUCCESS_FLAG;
            }
        }
    } catch (DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        msg+=",支付渠道ID ["+gid+"] 已存在!";
    } catch (Exception ee) {
        logger.info(ee.getMessage(), ee);
    }
    return msg;
}
 
開發者ID:wufeisoft,項目名稱:ryf_mms2,代碼行數:30,代碼來源:SysManageService.java

示例13: addConnection

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
public void addConnection(Connection<?> connection) {
    try {
        ConnectionData data = connection.createData();
        int rank = socialUserRepository.getRank(userId, data.getProviderId()) ;
        
        socialUserRepository.create(
            userId, 
            data.getProviderId(), 
            data.getProviderUserId(), 
            rank, 
            data.getDisplayName(), 
            data.getProfileUrl(), 
            data.getImageUrl(), 
            encrypt(data.getAccessToken()), 
            encrypt(data.getSecret()),
            encrypt(data.getRefreshToken()), 
            data.getExpireTime()
        );
    } catch (DuplicateKeyException e) {
        throw new DuplicateConnectionException(connection.getKey());
    }
}
 
開發者ID:alex-bretet,項目名稱:cloudstreetmarket.com,代碼行數:23,代碼來源:SocialUserConnectionRepositoryImpl.java

示例14: shouldNotRegisterTaskForBuildWhenTheTaskAlreadyExists

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@Test
public void shouldNotRegisterTaskForBuildWhenTheTaskAlreadyExists() throws Exception {
    buildOptional = of(build);
    phaseOptional = of(phase);
    taskOptional = of(task);
    when(buildRepository.findByNumber(eq(1))).thenReturn(buildOptional);
    when(phaseRepository.findByBuildAndName(eq(build), eq("phase"))).thenReturn(phaseOptional);
    doThrow(DuplicateKeyException.class).when(taskRepository).save(eq(task));
    try {
        service.register(1, "phase", task);
        fail();
    } catch (DuplicateKeyException e) {
    }
    verify(task).setState(isA(State.class));
    verify(task).setPhase(eq(phase));
    verify(buildRepository).findByNumber(eq(1));
    verify(phaseRepository).findByBuildAndName(eq(build), eq("phase"));
    verify(taskRepository).save(task);
}
 
開發者ID:Spectingular,項目名稱:spectingular.spock,代碼行數:20,代碼來源:TaskServiceTest.java

示例15: shouldNotRegisterTaskForModuleWhenTheTaskAlreadyExists

import org.springframework.dao.DuplicateKeyException; //導入依賴的package包/類
@Test
public void shouldNotRegisterTaskForModuleWhenTheTaskAlreadyExists() throws Exception {
    buildOptional = of(build);
    moduleOptional = of(module);
    phaseOptional = of(phase);
    taskOptional = of(task);
    when(buildRepository.findByNumber(eq(1))).thenReturn(buildOptional);
    when(moduleRepository.findByBuildAndName(eq(build), eq("module"))).thenReturn(moduleOptional);
    when(phaseRepository.findByModuleAndName(eq(module), eq("phase"))).thenReturn(phaseOptional);
    doThrow(DuplicateKeyException.class).when(taskRepository).save(eq(task));
    try {
        service.register(1, "module", "phase", task);
        fail();
    } catch (DuplicateKeyException e) {
    }
    verify(task).setState(isA(State.class));
    verify(task).setPhase(eq(phase));
    verify(buildRepository).findByNumber(eq(1));
    verify(moduleRepository).findByBuildAndName(eq(build), eq("module"));
    verify(phaseRepository).findByModuleAndName(eq(module), eq("phase"));
    verify(taskRepository).save(task);
}
 
開發者ID:Spectingular,項目名稱:spectingular.spock,代碼行數:23,代碼來源:TaskServiceTest.java


注:本文中的org.springframework.dao.DuplicateKeyException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。