当前位置: 首页>>代码示例>>Java>>正文


Java ConstraintViolationException类代码示例

本文整理汇总了Java中org.hibernate.exception.ConstraintViolationException的典型用法代码示例。如果您正苦于以下问题:Java ConstraintViolationException类的具体用法?Java ConstraintViolationException怎么用?Java ConstraintViolationException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ConstraintViolationException类属于org.hibernate.exception包,在下文中一共展示了ConstraintViolationException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: save

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
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);
    }
    
}
 
开发者ID:amritbhat786,项目名称:DocIT,代码行数:19,代码来源:DepartmentBean.java

示例2: save

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
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);
    }
    
}
 
开发者ID:amritbhat786,项目名称:DocIT,代码行数:23,代码来源:EmployeeBean.java

示例3: handleException

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
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);
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:27,代码来源:ServiceDispatcher.java

示例4: convert

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
/**
 * 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
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:27,代码来源:CacheSQLExceptionConversionDelegate.java

示例5: buildSQLExceptionConversionDelegate

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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;
		}
	};
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:20,代码来源:SybaseASE157Dialect.java

示例6: testPersist_alreadyExistingDifferent

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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());
}
 
开发者ID:santanusinha,项目名称:dropwizard-db-sharding-bundle,代码行数:26,代码来源:LockTest.java

示例7: create

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
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;
}
 
开发者ID:jokoframework,项目名称:notification-server,代码行数:19,代码来源:BaseDAO.java

示例8: updateDataSource

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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);
}
 
开发者ID:abixen,项目名称:abixen-platform,代码行数:19,代码来源:DataSourceController.java

示例9: createStateMachine

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:flipkart-incubator,项目名称:flux,代码行数:30,代码来源:StateMachineResource.java

示例10: emailJaCadastradoTest

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@Test(expected = ConstraintViolationException.class)
    public void emailJaCadastradoTest() {
//        try {
            Usuario usuario1 = new Usuario("Usuario1", 27, "[email protected]");
            Usuario usuario2 = new Usuario("Usuario2", 30, "[email protected]");
            assertEquals(usuario1.getEmail(), usuario2.getEmail());
            usuarioService.salvarOuAtualizar(usuario1);
            usuarioService.salvarOuAtualizar(usuario2);
//        } catch (Exception e) {
//            assertThat(e.getCause().getCause().getMessage(),
//                    anyOf(
//                            startsWith("integrity constraint violation: unique constraint or index violation"), // hsqldb constraint message
//                            startsWith("Unique index or primary key violation") // h2 constraint message
//                    ));
//        }
    }
 
开发者ID:thiaguten,项目名称:spring-noxml-crud,代码行数:17,代码来源:UsuarioTest.java

示例11: isCausedByConstraintViolationException

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:FINRAOS,项目名称:herd,代码行数:26,代码来源:HerdErrorInformationExceptionHandler.java

示例12: register

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
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;
}
 
开发者ID:ZSCNetSupportDept,项目名称:WechatTicketSystem,代码行数:27,代码来源:Register.java

示例13: itShouldThrowWhenEventAndSequenceNotUnique

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:caeos,项目名称:coner-core,代码行数:25,代码来源:RunDaoTest.java

示例14: testCouldNotSaveNonUniqueGID

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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);
}


}
 
开发者ID:gisgraphy,项目名称:gisgraphy,代码行数:18,代码来源:OpenStreetMapDaoTest.java

示例15: saveOrUpdate

import org.hibernate.exception.ConstraintViolationException; //导入依赖的package包/类
@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);
  }
}
 
开发者ID:epam-debrecen-rft-2015,项目名称:atsy,代码行数:17,代码来源:UserServiceImpl.java


注:本文中的org.hibernate.exception.ConstraintViolationException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。