public void save() {
try {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
department.setName(this.name);
daoFactory.getDepartmentDAO().makePersistent(department);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (ConstraintViolationException e) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
StringBuilder sb = new StringBuilder();
sb.append("Error: There is already a department with the name ");
sb.append(this.name);
sb.append(". Enter a valid name, please.");
FacesMessage facesMessage = new FacesMessage(sb.toString(), "name");
FacesContext.getCurrentInstance().addMessage("name", facesMessage);
}
}
java类org.hibernate.exception.ConstraintViolationException的实例源码
DepartmentBean.java 文件源码
项目:DocIT
阅读 29
收藏 0
点赞 0
评论 0
EmployeeBean.java 文件源码
项目:DocIT
阅读 29
收藏 0
点赞 0
评论 0
public void save() {
try {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
DAOFactory daoFactory = DAOFactory.instance(DAOFactory.HIBERNATE);
employee.setName(this.name);
employee.setAddress(this.address);
employee.setSalary(this.salary);
daoFactory.getEmployeeDAO().makePersistent(employee);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (ConstraintViolationException e) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
StringBuilder sb = new StringBuilder();
sb.append("Error: There is already an employee with the same name and address (name = ");
sb.append(this.name);
sb.append(", address = ");
sb.append(this.address);
sb.append("). Enter valid data, please.");
FacesMessage facesMessage = new FacesMessage(sb.toString(), "name");
FacesContext.getCurrentInstance().addMessage("name", facesMessage);
}
}
ServiceDispatcher.java 文件源码
项目:osc-core
阅读 39
收藏 0
点赞 0
评论 0
private void handleException(Throwable e)
throws VmidcDbConstraintViolationException, VmidcDbConcurrencyException, Exception {
if (e instanceof SslCertificatesExtendedException) {
throw (SslCertificatesExtendedException) e;
} else if (e instanceof VmidcException) {
log.warn("Service request failed (logically): " + e.getMessage());
} else {
log.error("Service request failed (unexpectedly): " + e.getMessage(), e);
}
if (e instanceof ConstraintViolationException) {
log.error("Got database constraint violation exception", e);
throw new VmidcDbConstraintViolationException("Database Constraint Violation Exception.");
} else if (e instanceof StaleObjectStateException) {
log.error("Got database concurrency exception", e);
throw new VmidcDbConcurrencyException("Database Concurrency Exception.");
} else if (e instanceof Exception) {
throw (Exception) e;
}
throw new Exception("Exception or error executing service call: " + e.getMessage(), e);
}
CacheSQLExceptionConversionDelegate.java 文件源码
项目:lams
阅读 32
收藏 0
点赞 0
评论 0
/**
* Convert the given SQLException into Hibernate's JDBCException hierarchy.
*
* @param sqlException The SQLException to be converted.
* @param message An optional error message.
* @param sql Optionally, the sql being performed when the exception occurred.
* @return The resulting JDBCException; returns null if it could not be converted.
*/
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
String sqlStateClassCode = JdbcExceptionHelper.extractSqlStateClassCode( sqlException );
if ( sqlStateClassCode != null ) {
Integer errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
if ( INTEGRITY_VIOLATION_CATEGORIES.contains( errorCode ) ) {
String constraintName =
getConversionContext()
.getViolatedConstraintNameExtracter()
.extractConstraintName( sqlException );
return new ConstraintViolationException( message, sqlException, sql, constraintName );
}
else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
return new DataException( message, sqlException, sql );
}
}
return null; // allow other delegates the chance to look
}
SybaseASE157Dialect.java 文件源码
项目:lams
阅读 36
收藏 0
点赞 0
评论 0
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
return new SQLExceptionConversionDelegate() {
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
if("JZ0TO".equals( sqlState ) || "JZ006".equals( sqlState )){
throw new LockTimeoutException( message, sqlException, sql );
}
if ( 515 == errorCode && "ZZZZZ".equals( sqlState ) ) {
// Attempt to insert NULL value into column; column does not allow nulls.
final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException );
return new ConstraintViolationException( message, sqlException, sql, constraintName );
}
return null;
}
};
}
LockTest.java 文件源码
项目:dropwizard-db-sharding-bundle
阅读 33
收藏 0
点赞 0
评论 0
@Test(expected = ConstraintViolationException.class)
public void testPersist_alreadyExistingDifferent() throws Exception {
SomeLookupObject p1 = SomeLookupObject.builder()
.myId("0")
.name("Parent 1")
.build();
lookupDao.save(p1);
SomeLookupObject p2 = SomeLookupObject.builder()
.myId("0")
.name("Changed")
.build();
lookupDao.saveAndGetExecutor(p2)
.filter(parent -> !Strings.isNullOrEmpty(parent.getName()))
.save(relationDao, parent -> SomeOtherObject.builder()
.my_id(parent.getMyId())
.value("Hello")
.build())
.execute();
Assert.assertEquals(p1.getMyId(), lookupDao.get("0").get().getMyId());
Assert.assertEquals("Changed", lookupDao.get("0").get().getName());
}
BaseDAO.java 文件源码
项目:notification-server
阅读 53
收藏 0
点赞 0
评论 0
public T create(T entity) throws HibernateException, SQLException {
Transaction t = getSession().getTransaction();
try {
t.begin();
getSession().saveOrUpdate(entity);
t.commit();
} catch (HibernateException e) {
if (t != null) {
LOGGER.error("ROLLBACK: " + entity);
t.rollback();
}
if (e instanceof ConstraintViolationException){
throw ((ConstraintViolationException)e).getSQLException();
}
throw e;
}
return entity;
}
DataSourceController.java 文件源码
项目:abixen-platform
阅读 28
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public FormValidationResultDto updateDataSource(@PathVariable("id") Long id, @RequestBody @Valid DataSourceForm dataSourceForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
List<FormErrorDto> formErrors = ValidationUtil.extractFormErrors(bindingResult);
return new FormValidationResultDto(dataSourceForm, formErrors);
}
try {
dataSourceFacade.updateDataSource(dataSourceForm);
} catch (Throwable e) {
log.error(e.getMessage());
if (e.getCause() instanceof ConstraintViolationException) {
throw new PlatformRuntimeException("Data source can not be updated. If you want to change available columns then you need to detach they from module firstly.");
} else {
throw e;
}
}
return new FormValidationResultDto(dataSourceForm);
}
StateMachineResource.java 文件源码
项目:flux
阅读 31
收藏 0
点赞 0
评论 0
/**
* Will instantiate a state machine in the flux execution engine
*
* @param stateMachineDefinition User input for state machine
* @return unique machineId of the instantiated state machine
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Timed
public Response createStateMachine(StateMachineDefinition stateMachineDefinition) throws Exception {
if (stateMachineDefinition == null)
throw new IllegalRepresentationException("State machine definition is empty");
StateMachine stateMachine = null;
try {
stateMachine = createAndInitStateMachine(stateMachineDefinition);
metricsClient.markMeter(new StringBuilder().
append("stateMachine.").
append(stateMachine.getName()).
append(".started").toString());
} catch (ConstraintViolationException ex) {
//in case of Duplicate correlation key, return http code 409 conflict
return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(ex.getCause() != null ? ex.getCause().getMessage() : null).build();
}
return Response.status(Response.Status.CREATED.getStatusCode()).entity(stateMachine.getId()).build();
}
HerdErrorInformationExceptionHandler.java 文件源码
项目:herd
阅读 30
收藏 0
点赞 0
评论 0
/**
* Returns {@code true} if the given throwable is or is not caused by a database constraint violation.
*
* @param exception - throwable to check.
*
* @return {@code true} if is constraint violation, {@code false} otherwise.
*/
private boolean isCausedByConstraintViolationException(Exception exception)
{
// some databases will throw ConstraintViolationException
boolean isConstraintViolation = ExceptionUtils.indexOfThrowable(exception, ConstraintViolationException.class) != -1;
// other databases will not throw a nice exception
if (!isConstraintViolation)
{
// We must manually check the error codes
Throwable rootThrowable = getRootCause(exception);
if (rootThrowable instanceof SQLException)
{
SQLException sqlException = (SQLException) rootThrowable;
isConstraintViolation = POSTGRES_SQL_STATE_CODE_FOREIGN_KEY_VIOLATION.equals(sqlException.getSQLState());
}
}
return isConstraintViolation;
}
Register.java 文件源码
项目:WechatTicketSystem
阅读 36
收藏 0
点赞 0
评论 0
private Object register(long sid, String name, ISP isp, String netAccount, int block, int room, long phone, String wechat) {
if (sid == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
if (name == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
if (isp == null) return Error.INVALID_PARAMETER.withMsg("Invalid_ISP");
if (netAccount == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Account");
if (block == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Block");
if (room == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Room");
if (phone == -1) return Error.INVALID_PARAMETER.withMsg("Invalid_Phone_Number");
User user = TableUser.getById(sid);
if (user == null) return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
if (!user.getName().equals(name)) return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
if (user.getWechatId() != null) return Error.INVALID_PARAMETER.withMsg("User_Already_Registered");
user.setIsp(isp);
user.setNetAccount(netAccount);
user.setBlock(block);
user.setRoom(room);
user.setPhone(phone);
user.setWechatId(wechat);
try {
TableUser.update(user);
} catch (ConstraintViolationException e) {
String dupKey = e.getConstraintName();
return Error.INVALID_PARAMETER.withMsg("Duplicated_" + dupKey.toUpperCase()); // PHONE ACCOUNT WECHAT
}
return Error.OK;
}
RunDaoTest.java 文件源码
项目:coner-core
阅读 27
收藏 0
点赞 0
评论 0
@Test
@Ignore("Deferring work on this, see https://github.com/caeos/coner-core/issues/181")
public void itShouldThrowWhenEventAndSequenceNotUnique() throws InterruptedException {
RunHibernateEntity entity1 = buildUnsavedRun();
entity1.setSequence(1);
RunHibernateEntity entity2 = buildUnsavedRun();
entity2.setSequence(1);
// sanity checks
assertThat(entity1.getEvent()).isSameAs(entity2.getEvent());
assertThat(entity1.getSequence()).isEqualTo(entity2.getSequence());
try {
daoTestRule.inTransaction(() -> {
dao.create(entity1);
dao.create(entity2);
failBecauseExceptionWasNotThrown(PersistenceException.class);
});
} catch (Exception e) {
assertThat(e)
.isInstanceOf(PersistenceException.class)
.hasCauseInstanceOf(ConstraintViolationException.class);
}
}
OpenStreetMapDaoTest.java 文件源码
项目:gisgraphy
阅读 26
收藏 0
点赞 0
评论 0
@Test
public void testCouldNotSaveNonUniqueGID(){
OpenStreetMap streetOSM = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
openStreetMapDao.save(streetOSM);
assertNotNull(openStreetMapDao.get(streetOSM.getId()));
OpenStreetMap streetOSM2 = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet();
try {
openStreetMapDao.save(streetOSM2);
openStreetMapDao.flushAndClear();
fail("we should not save street with non unique GID");
} catch (DataIntegrityViolationException e) {
assertTrue("a ConstraintViolationException should be throw when saving an openstreetmap with a non unique gid ",e.getCause() instanceof ConstraintViolationException);
}
}
UserServiceImpl.java 文件源码
项目:atsy
阅读 35
收藏 0
点赞 0
评论 0
@Transactional
@Override
public Long saveOrUpdate(UserDTO userDTO) {
Assert.notNull(userDTO);
UserEntity entity = converterService.convert(userDTO, UserEntity.class);
try {
return userRepository.saveAndFlush(entity).getId();
} catch (ConstraintViolationException | DataIntegrityViolationException ex) {
log.error("Save to repository failed.", ex);
String userName = entity.getUserName();
throw new DuplicateRecordException(userName,
"Duplication occurred when saving user: " + userName, ex);
}
}
CandidateServiceImplTest.java 文件源码
项目:atsy
阅读 27
收藏 0
点赞 0
评论 0
@Test
public void saveOrUpdateShouldThrowDREAfterCatchingConstraintViolationException()
throws DuplicateCandidateException {
// Given
given(converterService.convert(dummyCandidateDto, CandidateEntity.class))
.willReturn(dummyCandidateEntity);
given(candidateRepository.saveAndFlush(dummyCandidateEntity))
.willThrow(ConstraintViolationException.class);
expectedException.expect(DuplicateCandidateException.class);
expectedException.expectMessage(CoreMatchers.endsWith(NAME));
expectedException.expectCause(Matchers.isA(ConstraintViolationException.class));
// When
candidateService.saveOrUpdate(dummyCandidateDto);
// Then
}
PersistenceExceptionHandler.java 文件源码
项目:ums-backend
阅读 33
收藏 0
点赞 0
评论 0
@Override
@ResponseBody
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = {PersistenceException.class})
public MessageResource handle(final PersistenceException e) {
LOGGER.error("Handling persistence exception", e);
MessageResource message = new MessageResource();
message.setMessageType(MessageType.ERROR);
if (e.getCause() instanceof ConstraintViolationException) {
message.setMessage(MessageFormat.format("ConstraintViolationName : {0}", ((ConstraintViolationException) e.getCause()).getConstraintName()));
} else {
message.setMessage(e.getMessage());
}
return message;
}
AccountBase.java 文件源码
项目:zstack
阅读 26
收藏 0
点赞 0
评论 0
@Transactional
private void handle(APIAttachPoliciesToUserMsg msg) {
for (String puuid : msg.getPolicyUuids()) {
try {
UserPolicyRefVO refVO = new UserPolicyRefVO();
refVO.setUserUuid(msg.getUserUuid());
refVO.setPolicyUuid(puuid);
dbf.getEntityManager().persist(refVO);
dbf.getEntityManager().flush();
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
}
APIAttachPoliciesToUserEvent evt = new APIAttachPoliciesToUserEvent(msg.getId());
bus.publish(evt);
}
AccountBase.java 文件源码
项目:zstack
阅读 26
收藏 0
点赞 0
评论 0
private void handle(APIAttachPolicyToUserGroupMsg msg) {
UserGroupPolicyRefVO grvo = new UserGroupPolicyRefVO();
grvo.setGroupUuid(msg.getGroupUuid());
grvo.setPolicyUuid(msg.getPolicyUuid());
try {
dbf.persist(grvo);
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
APIAttachPolicyToUserGroupEvent evt = new APIAttachPolicyToUserGroupEvent(msg.getId());
bus.publish(evt);
}
AccountBase.java 文件源码
项目:zstack
阅读 27
收藏 0
点赞 0
评论 0
private void handle(APIAttachPolicyToUserMsg msg) {
UserPolicyRefVO upvo = new UserPolicyRefVO();
upvo.setPolicyUuid(msg.getPolicyUuid());
upvo.setUserUuid(msg.getUserUuid());
try {
dbf.persist(upvo);
} catch (Throwable t) {
if (!ExceptionDSL.isCausedBy(t, ConstraintViolationException.class)) {
throw t;
}
// the policy is already attached
}
APIAttachPolicyToUserEvent evt = new APIAttachPolicyToUserEvent(msg.getId());
bus.publish(evt);
}
CommonUtil.java 文件源码
项目:Lucee4
阅读 41
收藏 0
点赞 0
评论 0
public static PageException toPageException(Throwable t) {
lucee.commons.lang.ExceptionUtil.rethrowIfNecessary(t);
PageException pe = caster().toPageException(t);;
if (t instanceof org.hibernate.HibernateException) {
org.hibernate.HibernateException he = (org.hibernate.HibernateException)t;
Throwable cause = he.getCause();
if(cause != null) {
pe = caster().toPageException( cause );
ExceptionUtil.setAdditional(pe, CommonUtil.createKey("hibernate exception"), t );
}
}
if ( t instanceof JDBCException ) {
JDBCException je = (JDBCException)t;
ExceptionUtil.setAdditional(pe, CommonUtil.createKey("sql"), je.getSQL());
}
if( t instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException)t;
if(!Util.isEmpty(cve.getConstraintName())) {
ExceptionUtil.setAdditional(pe, CommonUtil.createKey("constraint name"), cve.getConstraintName());
}
}
return pe;
}
AbstractFrontendController.java 文件源码
项目:jspresso-ce
阅读 28
收藏 0
点赞 0
评论 0
/**
* Refines the data integrity violation exception to determine the translation
* key from which the user message will be constructed.
*
* @param exception
* the DataIntegrityViolationException.
* @return the translation key to use.
*/
protected String refineIntegrityViolationTranslationKey(DataIntegrityViolationException exception) {
if (exception.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException cve = (ConstraintViolationException) exception.getCause();
if (cve.getSQL() != null && cve.getSQL().toUpperCase().contains("DELETE")) {
return "error.fk.delete";
}
if (cve.getConstraintName() != null) {
if (cve.getConstraintName().toUpperCase().contains("FK")) {
return "error.fk.update";
}
return "error.unicity";
}
return "error.integrity";
}
return "error.integrity";
}
MappingExceptionResolver.java 文件源码
项目:gomall.la
阅读 23
收藏 0
点赞 0
评论 0
/**
* Gets the exception message.
*
* @param e
* the e
* @return the exception message
*/
public void getExceptionMessage(UserMessages uem, Exception e,String errorCode ) {
Throwable throwable = e;
if (throwable.getCause() != null) {
throwable = throwable.getCause();
}
String title = ResourceBundleHelper.getString("error.code." + errorCode);
if(AppUtils.isNotBlank(title)){
uem.setTitle(title);
}else{
String errCode = null;
if ((throwable instanceof ConstraintViolationException) || (throwable instanceof BatchUpdateException) || (throwable instanceof DataIntegrityViolationException)) {
errCode = ErrorCodes.RESOURCE_CONFLICT;
}else if (throwable instanceof NullPointerException) {
errCode = ErrorCodes.ENTITY_NO_FOUND;
}
uem.setTitle(ResourceBundleHelper.getString("error.code." + errCode));
}
uem.setDesc(throwable.getMessage());
}
HibernateTradingDayPricesDao.java 文件源码
项目:systematic-trading
阅读 35
收藏 0
点赞 0
评论 0
@Override
public void create( final TradingDayPrices[] data ) {
final Session session = HibernateUtil.sessionFactory().getCurrentSession();
final Transaction tx = session.beginTransaction();
for (final TradingDayPrices d : data) {
try {
create(d, session);
} catch (final HibernateException e) {
if (e.getCause() instanceof ConstraintViolationException) {
// Only constraint violation here will be primary key, or attempting to insert
// data already present
LOG.debug(e.getMessage());
} else {
throw e;
}
}
}
tx.commit();
}
CommentaryServiceImpl.java 文件源码
项目:zlogger
阅读 35
收藏 0
点赞 0
评论 0
@Override
@Transactional
public Long add(Commentary entity) {
Objects.requireNonNull(entity, "Can't add null commentary");
User user = entity.getCreator();
Post post = entity.getPost();
Objects.requireNonNull(post, "Can't add commentary with null post");
Objects.requireNonNull(user, "Can't add commentary with null creator");
Objects.requireNonNull(post.getId(), "Can't add commentary with null post_id");
Objects.requireNonNull(user.getUsername(),
"Can't add commentary with null creator_name");
if (!user.getEnabled()) {
throw new IllegalStateException("Can't add commentary with disabled creator");
}
entity.setCreationDate(new Date());
try {
return commentaryDao.create(entity);
} catch (ConstraintViolationException e) {
LOGGER.log(Level.WARNING, e.toString());
throw new IllegalArgumentException("Commentary is malformed or it's " +
"dependencies are not persistent. " +
"Violated constraint: " + e.getConstraintName());
}
}
TransactionRetryerITCaseNew.java 文件源码
项目:olat
阅读 23
收藏 0
点赞 0
评论 0
@Test
public void testSubscribe_IfCoreServiceThrowsException_checkNumberOfRetries() {
NotificationService mockNotificationService = mock(NotificationService.class);
when(mockNotificationService.subscribe(notificationSubscriptionContext1)).thenThrow(new ConstraintViolationException(IDENTITY_NAME_1, null, IDENTITY_NAME_1));
learnServiceImpl.setNotificationService(mockNotificationService);
try {
verify(learnServiceImpl.subscribe(notificationSubscriptionContext1));
} catch (Exception e) {
System.out.println("catch to check for number of retries");
}
// the number of retries for ConstraintViolationException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
verify(mockNotificationService, times(2)).subscribe(notificationSubscriptionContext1);
}
TransactionRetryerITCaseNew.java 文件源码
项目:olat
阅读 29
收藏 0
点赞 0
评论 0
@Test
public void isRetryStillAllowed_oneExceptionType_oneRetryAllowed() {
Map<String, Long> retriesPerException = new HashMap<String, Long>();
assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry once allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry second time no more allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry no more allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
TransactionRetryerITCaseNew.java 文件源码
项目:olat
阅读 27
收藏 0
点赞 0
评论 0
@Test
public void testSubscribe_IfCoreServiceThrowsException_checkNumberOfRetries() {
NotificationService mockNotificationService = mock(NotificationService.class);
when(mockNotificationService.subscribe(notificationSubscriptionContext1)).thenThrow(new ConstraintViolationException(IDENTITY_NAME_1, null, IDENTITY_NAME_1));
learnServiceImpl.setNotificationService(mockNotificationService);
try {
verify(learnServiceImpl.subscribe(notificationSubscriptionContext1));
} catch (Exception e) {
System.out.println("catch to check for number of retries");
}
// the number of retries for ConstraintViolationException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
verify(mockNotificationService, times(2)).subscribe(notificationSubscriptionContext1);
}
TransactionRetryerITCaseNew.java 文件源码
项目:olat
阅读 26
收藏 0
点赞 0
评论 0
@Test
public void isRetryStillAllowed_oneExceptionType_oneRetryAllowed() {
Map<String, Long> retriesPerException = new HashMap<String, Long>();
assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry once allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry second time no more allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
// retry no more allowed
transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
UIDAOServiceImpl.java 文件源码
项目:openeos
阅读 30
收藏 0
点赞 0
评论 0
@Override
@Transactional(readOnly = false, rollbackFor = { UIDAOCoinstraintValidationException.class })
public void save(UIBean bean) throws UIDAOCoinstraintValidationException {
if (bean instanceof UIBeanImpl) {
UIBeanImpl uiBeanI = (UIBeanImpl) bean;
Session ses = getSession();
Object id = dictionaryService.getClassDefinition(uiBeanI.getBeanWrapped().getClass()).getIdPropertyDefinition()
.get(uiBeanI.getBeanWrapped());
try {
ses.saveOrUpdate(uiBeanI.getBeanWrapped());
ses.flush();
uiBeanI.fireOnSave();
} catch (HibernateException ex) {
// See https://hibernate.atlassian.net/browse/HB-1014
dictionaryService.getClassDefinition(uiBeanI.getBeanWrapped().getClass()).getIdPropertyDefinition()
.set(uiBeanI.getBeanWrapped(), id);
if (ex instanceof ConstraintViolationException) {
ConstraintViolationException constraintException = (ConstraintViolationException) ex;
throw new UIDAOCoinstraintValidationException(constraintException);
}
throw ex;
}
} else {
throw new UnsupportedOperationException("Don't recognice bean passes as argument, must be UIBeanImpl class.");
}
}
PostgreSQLDialectBatchUpdateResolver.java 文件源码
项目:openeos
阅读 24
收藏 0
点赞 0
评论 0
@Override
protected Throwable unencapsuleThrowable(Throwable t) {
if (t instanceof ConstraintViolationException) {
ConstraintViolationException constrainEx = (ConstraintViolationException) t;
if (constrainEx.getConstraintName() == null) {
SQLException sqlEx = constrainEx.getSQLException();
if (sqlEx instanceof BatchUpdateException) {
SQLException other = sqlEx.getNextException();
if (other != null) {
String constraintName = conversionContext.getViolatedConstraintNameExtracter().extractConstraintName(other);
if (constraintName != null) {
return new ConstraintViolationException(t.getMessage(), sqlEx, constraintName);
}
}
}
}
}
return null;
}