Java 类org.hibernate.NonUniqueObjectException 实例源码

项目:TomboloDigitalConnector    文件:TimedValueUtils.java   
public static int save(List<TimedValue> timedValues){
    return HibernateUtil.withSession((session) -> {
        int saved = 0;
        session.beginTransaction();
        for (TimedValue timedValue : timedValues){
            try{
                session.saveOrUpdate(timedValue);
                saved++;
            }catch(NonUniqueObjectException e){
                // This is happening because the TFL stations contain a duplicate ID
                log.warn("Could not save timed value for subject {}, attribute {}, time {}: {}",
                        timedValue.getId().getSubject().getLabel(),
                        timedValue.getId().getAttribute().getDescription(),
                        timedValue.getId().getTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                        e.getMessage());
            }
            if ( saved % 20 == 0 ) { //20, same as the JDBC batch size
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }
        session.getTransaction().commit();
        return saved;
    });
}
项目:TomboloDigitalConnector    文件:FixedValueUtils.java   
public static int save(List<FixedValue> fixedValues){
    return HibernateUtil.withSession((session) -> {
        int saved = 0;
        session.beginTransaction();
        for (FixedValue fixedValue : fixedValues){
            try{
                session.saveOrUpdate(fixedValue);
                saved++;
            }catch(NonUniqueObjectException e){
                // This is happening because the TFL stations contain a duplicate ID
                log.warn("Could not save fixed value for subject {}, attribute {}: {}",
                        fixedValue.getId().getSubject().getLabel(),
                        fixedValue.getId().getAttribute().getLabel(),
                        e.getMessage());
            }
            if ( saved % 20 == 0 ) { //20, same as the JDBC batch size
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }
        session.getTransaction().commit();
        return saved;
    });
}
项目:cacheonix-core    文件:MergeTest.java   
public void testPersistThenMergeInSameTxnWithVersion() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    VersionedEntity entity = new VersionedEntity( "test", "test" );
    s.persist( entity );
    s.merge( new VersionedEntity( "test", "test-2" ) );

    try {
        // control operation...
        s.saveOrUpdate( new VersionedEntity( "test", "test-3" ) );
        fail( "saveOrUpdate() should fail here" );
    }
    catch( NonUniqueObjectException expected ) {
        // expected behavior
    }

    tx.commit();
    s.close();

    cleanup();
}
项目:cacheonix-core    文件:MergeTest.java   
public void testPersistThenMergeInSameTxnWithTimestamp() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    TimestampedEntity entity = new TimestampedEntity( "test", "test" );
    s.persist( entity );
    s.merge( new TimestampedEntity( "test", "test-2" ) );

    try {
        // control operation...
        s.saveOrUpdate( new TimestampedEntity( "test", "test-3" ) );
        fail( "saveOrUpdate() should fail here" );
    }
    catch( NonUniqueObjectException expected ) {
        // expected behavior
    }

    tx.commit();
    s.close();

    cleanup();
}
项目:eurocarbdb    文件:HibernateEntityManager.java   
@SuppressWarnings("unchecked") 
// ^^^ unavoidable, due to lack of genericity in Hibernate lib
public <T> T lookup( Class<T> c, int object_id ) 
{
    if ( log.isDebugEnabled() )
        log.debug( "attempting to lookup object of " 
                 + c.getName() 
                 + " with id=" 
                 + object_id );

    try
    {
        Session session = getHibernateSession();
        T entity = (T) session.get( c, object_id );
        return entity;
    }
    catch ( NonUniqueObjectException e )
    {
        __log_exception( e, c );
        throw e;
    }
}
项目:eurocarbdb    文件:HibernateEntityManager.java   
public <T> void lookup( T destinationObject, int objectId ) 
{
    if ( log.isDebugEnabled() )
    {
        log.debug( "attempting to populate existing object " 
                 + destinationObject
                 + " with id=" 
                 + objectId 
                 );
    }

    try
    {
        Session session = getHibernateSession();
        session.load(destinationObject, objectId);
    }
    catch ( NonUniqueObjectException e )
    {
        __log_exception( e, destinationObject );
        throw e;
    }
}
项目:cmdit    文件:SaveAbstractObjCmd.java   
@Override
public Command runCommand() throws Exception {
    isUpdate = (object.getPid() != null);
    T aux = completeObject(object);

    try{
        object = (aux != null)?aux:object;
        dao.persist(object);
    }catch(NonUniqueObjectException nuoe){
        if(autoMerge){
            dao.merge(object);
        }else
            throw nuoe;
    }

    return this;
}
项目:JForum    文件:CategoryDAOTestCase.java   
@Test(expected=NonUniqueObjectException.class)
public void updateChangingAnInstanceCreatedByHandUsingARealIdShouldFail() {
    CategoryRepository dao = this.newDao();
    Category c = this.newCategory("c1", false);
    this.insert(c, dao);
    this.commit();

    int id = c.getId();

    Category c2 = new Category();
    c2.setId(id);
    c2.setName("c2");
    c2.setModerated(true);
    c2.setDisplayOrder(2);

    this.update(c2, dao);

    Category loaded = dao.get(id);
    Assert.assertEquals("c2", loaded.getName());
    Assert.assertEquals(true, loaded.isModerated());
    Assert.assertEquals(2, loaded.getDisplayOrder());
}
项目:jspresso-ce    文件:HibernateBackendController.java   
/**
 * Locks an entity (LockMode.NONE) in current hibernate session.
 *
 * @param entity
 *     the entity to lock.
 * @param hibernateSession
 *     the hibernate session.
 */
private void lockInHibernate(IEntity entity, Session hibernateSession) {
  if (!hibernateSession.contains(entity)) {
    // Do not use get before trying to lock.
    // Get performs a DB query.
    try {
      hibernateSession.buildLockRequest(LockOptions.NONE).lock(entity);
    } catch (NonUniqueObjectException ex) {
      if (hibernateSession == noTxSession) {
        hibernateSession.clear();
        hibernateSession.buildLockRequest(LockOptions.NONE).lock(entity);
      } else {
        throw ex;
      }
    }
  }
}
项目:lams    文件:StatefulPersistenceContext.java   
@Override
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
    final Object entity = getEntity( key );
    if ( entity == object ) {
        throw new AssertionFailure( "object already associated, but no entry was found" );
    }
    if ( entity != null ) {
        throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
    }
}
项目:lams    文件:DefaultLoadEventListener.java   
/**
 * Performs the load of an entity.
 *
 * @param event The initiating load request event
 * @param persister The persister corresponding to the entity to be loaded
 * @param keyToLoad The key of the entity to be loaded
 * @param options The defined load options
 *
 * @return The loaded entity.
 *
 * @throws HibernateException
 */
protected Object load(
        final LoadEvent event,
        final EntityPersister persister,
        final EntityKey keyToLoad,
        final LoadEventListener.LoadType options) {

    if ( event.getInstanceToLoad() != null ) {
        if ( event.getSession().getPersistenceContext().getEntry( event.getInstanceToLoad() ) != null ) {
            throw new PersistentObjectException(
                    "attempted to load into an instance that was already associated with the session: " +
                            MessageHelper.infoString(
                                    persister,
                                    event.getEntityId(),
                                    event.getSession().getFactory()
                            )
            );
        }
        persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), event.getSession() );
    }

    Object entity = doLoad( event, persister, keyToLoad, options );

    boolean isOptionalInstance = event.getInstanceToLoad() != null;

    if ( !options.isAllowNulls() || isOptionalInstance ) {
        if ( entity == null ) {
            event.getSession()
                    .getFactory()
                    .getEntityNotFoundDelegate()
                    .handleEntityNotFound( event.getEntityClassName(), event.getEntityId() );
        }
    }

    if ( isOptionalInstance && entity != event.getInstanceToLoad() ) {
        throw new NonUniqueObjectException( event.getEntityId(), event.getEntityClassName() );
    }

    return entity;
}
项目:cacheonix-core    文件:StatefulPersistenceContext.java   
/**
 * Attempts to check whether the given key represents an entity already loaded within the
 * current session.
 * @param object The entity reference against which to perform the uniqueness check.
 * @throws HibernateException
 */
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
    Object entity = getEntity(key);
    if ( entity == object ) {
        throw new AssertionFailure( "object already associated, but no entry was found" );
    }
    if ( entity != null ) {
        throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
    }
}
项目:cacheonix-core    文件:DefaultLoadEventListener.java   
/**
 * Perfoms the load of an entity.
 *
 * @return The loaded entity.
 * @throws HibernateException
 */
protected Object load(
    final LoadEvent event, 
    final EntityPersister persister, 
    final EntityKey keyToLoad, 
    final LoadEventListener.LoadType options)
throws HibernateException {

    if ( event.getInstanceToLoad() != null ) {
        if ( event.getSession().getPersistenceContext().getEntry( event.getInstanceToLoad() ) != null ) {
            throw new PersistentObjectException(
                    "attempted to load into an instance that was already associated with the session: " +
                    MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() )
                );
        }
        persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), event.getSession().getEntityMode() );
    }

    Object entity = doLoad(event, persister, keyToLoad, options);

    boolean isOptionalInstance = event.getInstanceToLoad() != null;

    if ( !options.isAllowNulls() || isOptionalInstance ) {
        if ( entity == null ) {
            event.getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( event.getEntityClassName(), event.getEntityId() );
        }
    }

    if ( isOptionalInstance && entity != event.getInstanceToLoad() ) {
        throw new NonUniqueObjectException( event.getEntityId(), event.getEntityClassName() );
    }

    return entity;
}
项目:eurocarbdb    文件:HibernateEntityManager.java   
public <T> void store( T entity ) 
{
    if ( log.isDebugEnabled() )
        log.debug( "attempting to store (make persistent) object " 
                 + entity
                 );

    Session s = getHibernateSession();

    if ( entity instanceof EurocarbObject )
        validate( (EurocarbObject) entity );

    try
    {
        s.save( entity );
        //s.saveOrUpdate( entity );
    }
    catch ( NonUniqueObjectException ex )
    {
        log.warn( "passed " 
             + entity.getClass().getSimpleName() 
             + " was originally loaded in a different Session"
             + "; attempting to merge changes..."
             , ex 
         );

        s.merge( entity );   
        log.debug( "changes merged ok" );
    }
}
项目:eurocarbdb    文件:HibernateEntityManager.java   
private final void __log_exception( NonUniqueObjectException e, Object entity )
{
    log.warn( "Caught NonUniqueObjectException while working with "
            + entity.getClass().getName()
            + ". This often means that you need to (re-)implement "
            + "the equals(Object) & hashCode() methods in this class "
            + "so that objects in the session can be compared for "
            + "*equality* rather than *identity*.",
            e
            );
}
项目:AlgoTrader    文件:HibernateUtil.java   
public static boolean lock(SessionFactory sessionFactory, Object target) {

        Session session = sessionFactory.getCurrentSession();

        try {
            session.buildLockRequest(LockOptions.NONE).lock(target);
            return true;
        } catch (NonUniqueObjectException e) {
            //  different object with the same identifier value was already associated with the session
            return false;
        }
    }
项目:uimaster    文件:BEEntityDaoObject.java   
/**
 * Update a business entity record to database.
 * 
 * @param entity
 */
@Transactional
public void update(IPersistentEntity entity, boolean commit) {
    if (logger.isDebugEnabled()) {
        logger.debug("Update an entity: {}", entity);
    }

    if (entity.getCreateDate() == null) {
        entity.setCreateDate(new Date());
    }
    if (testMode) {
        return;
    }

    // dirty data check!
    if (!exist(entity.getId(), entity.getCas(), entity.getClass())) {
        throw new RuntimeException("A dirty record found! update failed: " + entity.toString());
    }

    Session session = HibernateUtil.getSession();
    try {
        entity.setCas(System.currentTimeMillis());
        session.update(entity);
    } catch (NonUniqueObjectException e) {
        // try committing session again.
        session.update(entity);
    }

    if (commit) {
        HibernateUtil.releaseSession(session, true);
    }
}
项目:lams    文件:AbstractSaveEventListener.java   
/**
 * Prepares the save call by checking the session caches for a pre-existing
 * entity and performing any lifecycle callbacks.
 *
 * @param entity The entity to be saved.
 * @param id The id by which to save the entity.
 * @param persister The entity's persister instance.
 * @param useIdentityColumn Is an identity column being used?
 * @param anything Generally cascade-specific information.
 * @param source The session from which the event originated.
 * @param requiresImmediateIdAccess does the event context require
 * access to the identifier immediately after execution of this method (if
 * not, post-insert style id generators may be postponed if we are outside
 * a transaction).
 *
 * @return The id used to save the entity; may be null depending on the
 *         type of id generator used and the requiresImmediateIdAccess value
 */
protected Serializable performSave(
        Object entity,
        Serializable id,
        EntityPersister persister,
        boolean useIdentityColumn,
        Object anything,
        EventSource source,
        boolean requiresImmediateIdAccess) {

    if ( LOG.isTraceEnabled() ) {
        LOG.tracev( "Saving {0}", MessageHelper.infoString( persister, id, source.getFactory() ) );
    }

    final EntityKey key;
    if ( !useIdentityColumn ) {
        key = source.generateEntityKey( id, persister );
        Object old = source.getPersistenceContext().getEntity( key );
        if ( old != null ) {
            if ( source.getPersistenceContext().getEntry( old ).getStatus() == Status.DELETED ) {
                source.forceFlush( source.getPersistenceContext().getEntry( old ) );
            }
            else {
                throw new NonUniqueObjectException( id, persister.getEntityName() );
            }
        }
        persister.setIdentifier( entity, id, source );
    }
    else {
        key = null;
    }

    if ( invokeSaveLifecycle( entity, persister, source ) ) {
        return id; //EARLY EXIT
    }

    return performSaveOrReplicate(
            entity,
            key,
            persister,
            useIdentityColumn,
            anything,
            source,
            requiresImmediateIdAccess
    );
}
项目:cacheonix-core    文件:AbstractSaveEventListener.java   
/**
 * Ppepares the save call by checking the session caches for a pre-existing
 * entity and performing any lifecycle callbacks.
 *
 * @param entity The entity to be saved.
 * @param id The id by which to save the entity.
 * @param persister The entity's persister instance.
 * @param useIdentityColumn Is an identity column being used?
 * @param anything Generally cascade-specific information.
 * @param source The session from which the event originated.
 * @param requiresImmediateIdAccess does the event context require
 * access to the identifier immediately after execution of this method (if
 * not, post-insert style id generators may be postponed if we are outside
 * a transaction).
 *
 * @return The id used to save the entity; may be null depending on the
 *         type of id generator used and the requiresImmediateIdAccess value
 */
protected Serializable performSave(
        Object entity,
        Serializable id,
        EntityPersister persister,
        boolean useIdentityColumn,
        Object anything,
        EventSource source,
        boolean requiresImmediateIdAccess) {

    if ( log.isTraceEnabled() ) {
        log.trace(
                "saving " +
                        MessageHelper.infoString( persister, id, source.getFactory() )
        );
    }

    EntityKey key;
    if ( !useIdentityColumn ) {
        key = new EntityKey( id, persister, source.getEntityMode() );
        Object old = source.getPersistenceContext().getEntity( key );
        if ( old != null ) {
            if ( source.getPersistenceContext().getEntry( old ).getStatus() == Status.DELETED ) {
                source.forceFlush( source.getPersistenceContext().getEntry( old ) );
            }
            else {
                throw new NonUniqueObjectException( id, persister.getEntityName() );
            }
        }
        persister.setIdentifier( entity, id, source.getEntityMode() );
    }
    else {
        key = null;
    }

    if ( invokeSaveLifecycle( entity, persister, source ) ) {
        return id; //EARLY EXIT
    }

    return performSaveOrReplicate(
            entity,
            key,
            persister,
            useIdentityColumn,
            anything,
            source,
            requiresImmediateIdAccess
    );
}
项目:sakai    文件:ContextMappingDAOTest.java   
@Test(expected = NonUniqueObjectException.class)
public void testAddAdd() {
    dao.add("uuid", "componentId", "contextId1");
    dao.add("uuid", "componentId", "contextId2");
}
项目:sakai    文件:ContextMappingDAOTest.java   
@Test(expected = NonUniqueObjectException.class)
public void testAddAdd() {
    dao.add("uuid", "componentId", "contextId1");
    dao.add("uuid", "componentId", "contextId2");
}
项目:spacewalk    文件:ActivationKeyCloneCommand.java   
/**
 * Construct a ActivationKeyCloneCommand
 * @param userIn user doing the cloning
 * @param key Activation key to be cloned
 * @param cloneDescription The description of the cloned key.
 */
public ActivationKeyCloneCommand(User userIn, String key,
        String cloneDescription) {

    ActivationKeyManager akm = ActivationKeyManager.getInstance();
    ActivationKey ak = lookupKey(key, userIn);

    try {
        cak = akm.createNewActivationKey(userIn, "", cloneDescription,
                ak.getUsageLimit(), ak.getBaseChannel(), false);
        // only one akey can be Universal default
    }
    catch (ValidatorException ve) { // the user is not allowed to create AK
        throw FaultException.create(1091, "activationkey", ve.getResult());
    }
    catch (NonUniqueObjectException e) {
        throw new ActivationKeyAlreadyExistsException();
    }

    // enable/disable
    cak.setDisabled(ak.isDisabled());

    // Entitlements
    Set<ServerGroupType> cloneEnt = new HashSet<ServerGroupType>();
    cloneEnt.addAll(ak.getEntitlements());
    cak.setEntitlements(cloneEnt);

    // child channels
    Set<Channel> channels = new HashSet<Channel>();
    channels.addAll(ak.getChannels());
    cak.setChannels(channels);

    // Configuration File Deployment
    cak.setDeployConfigs(ak.getDeployConfigs());

    // packages
    for (Iterator<TokenPackage> it = ak.getPackages().iterator(); it
            .hasNext();) {
        TokenPackage temp = it.next();
        cak.addPackage(temp.getPackageName(), temp.getPackageArch());
    }

    // Configuration channels
    List<String> lcloneConfigChannels = new ArrayList<String>();
    for (Iterator<ConfigChannel> it = ak.getConfigChannelsFor(userIn)
            .iterator(); it.hasNext();) {
        lcloneConfigChannels.add(it.next().getLabel());
    }

    List<String> lcak = new ArrayList<String>();
    lcak.add(cak.getKey());
    setConfigChannels(userIn, lcak, lcloneConfigChannels);

    // Groups
    Set<ServerGroup> cloneServerGroups = new HashSet<ServerGroup>();
    cloneServerGroups.addAll(ak.getServerGroups());
    cak.setServerGroups(cloneServerGroups);
}