当前位置: 首页>>代码示例>>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;未经允许,请勿转载。