本文整理汇总了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);
}
}
示例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);
}
}
示例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);
}
示例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
}
示例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;
}
};
}
示例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());
}
示例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;
}
示例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);
}
示例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();
}
示例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
// ));
// }
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
}
示例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);
}
}