當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。