Пример #1
0
 public static void testTtansaction_1() {
   for (User user : getSession().findAll(User.class)) {
     getSession().delete(User.class, user.getId());
   }
   Transaction transaction = getSession().getTransaction();
   transaction.begin();
   User user = new User();
   try {
     user.setId(1231234);
     getSession().insert(user);
     user = getSession().find(User.class, "1231234");
     System.out.println("1:" + user);
     user.setName("123");
     getSession().update(user);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     transaction.end();
   }
   user = getSession().find(User.class, "1231234");
   System.out.println("2" + user);
   System.out.println("==========");
   transaction = getSession().getTransaction();
   transaction.begin();
   user = new User();
   try {
     user.setId(1231234567);
     getSession().insert(user);
     user = getSession().find(User.class, "1231234567");
     System.out.println("1:" + user);
     user.setName("123");
     getSession().update(user);
     transaction.submit();
   } finally {
     transaction.end();
   }
   user = getSession().find(User.class, "1231234567");
   System.out.println("2" + user);
   System.out.println("==========");
   transaction = getSession().getTransaction();
   transaction.begin();
   user = new User();
   try {
     user.setId(12312345);
     getSession().insert(user);
     user = getSession().find(User.class, "12312345");
     System.out.println("1:" + user);
     user.setName("123");
     getSession().update(user);
     transaction.submit();
   } finally {
     transaction.end();
   }
   user = getSession().find(User.class, "12312345");
   System.out.println("2" + user);
 }
Пример #2
0
  /**
   * Look up and return the ClassInfo for an integer handle. This is used when decoding an <code>
   * Object</code> from a <code>com.persistit.Value</code> to associate the encoded integer handle
   * value with the corresponding class.
   *
   * @param handle The handle
   * @return The associated ClassInfo, or <i>null</i> if there is none.
   */
  public ClassInfo lookupByHandle(final int handle) {
    final AtomicReferenceArray<ClassInfoEntry> hashTable = _hashTable;
    ClassInfoEntry cie = hashTable.get(handle % hashTable.length());
    while (cie != null) {
      if (cie._classInfo.getHandle() == handle) return cie._classInfo;
      cie = cie._next;
    }

    _cacheMisses.incrementAndGet();

    synchronized (this) {
      _sessionId.assign();
      Exchange ex = null;
      try {
        ex = getExchange();
        final Transaction txn = ex.getTransaction();
        txn.begin();
        try {
          ex.clear().append(BY_HANDLE).append(handle).fetch();
          txn.commit();
        } catch (final Exception e) {
          _persistit.getLogBase().exception.log(e);
          throw new ConversionException(e);
        } finally {
          txn.end();
        }
        final Value value = ex.getValue();
        if (value.isDefined()) {
          value.setStreamMode(true);
          final int storedId = value.getInt();
          final String storedName = value.getString();
          final long storedSuid = value.getLong();
          if (storedId != handle) {
            throw new IllegalStateException(
                "ClassInfo stored for handle=" + handle + " has invalid stored handle=" + storedId);
          }
          final Class<?> cl =
              Class.forName(storedName, false, Thread.currentThread().getContextClassLoader());

          long suid = 0;
          final ObjectStreamClass osc = ObjectStreamClass.lookupAny(cl);
          if (osc != null) suid = osc.getSerialVersionUID();
          if (storedSuid != suid) {
            throw new ConversionException(
                "Class "
                    + cl.getName()
                    + " persistent SUID="
                    + storedSuid
                    + " does not match current class SUID="
                    + suid);
          }
          final ClassInfo ci = new ClassInfo(cl, suid, handle, osc);
          hashClassInfo(ci);
          return ci;
        } else {
          final ClassInfo ci = new ClassInfo(null, 0, handle, null);
          hashClassInfo(ci);
          return ci;
        }
      } catch (final ClassNotFoundException cnfe) {
        throw new ConversionException(cnfe);
      } catch (final PersistitException pe) {
        throw new ConversionException(pe);
      } finally {
        if (ex != null) releaseExchange(ex);
      }
    }
  }
Пример #3
0
  /**
   * Look up and return the ClassInfo for a class. This is used when encoding an <code>Object</code>
   * into a <code>com.persistit.Value</code>.
   *
   * @param clazz The <code>Class</code>
   * @return The ClassInfo for the specified Class.
   */
  public ClassInfo lookupByClass(final Class<?> clazz) {
    final AtomicReferenceArray<ClassInfoEntry> hashTable = _hashTable;

    ObjectStreamClass osc = null;
    long suid = 0;

    final int nh = clazz.getName().hashCode() & 0x7FFFFFFF;
    ClassInfoEntry cie = hashTable.get(nh % hashTable.length());

    while (cie != null) {
      if (clazz.equals(cie._classInfo.getDescribedClass())) {
        return cie._classInfo;
      }
      if (cie._classInfo.getDescribedClass() != null
          && cie._classInfo.getName().equals(clazz.getName())) {
        if (osc == null) {
          osc = ObjectStreamClass.lookupAny(clazz);
          if (osc != null) {
            suid = osc.getSerialVersionUID();
          }
        }
        if (suid == cie._classInfo.getSUID()) {
          return cie._classInfo;
        }
      }
      cie = cie._next;
    }

    if (osc == null) {
      osc = ObjectStreamClass.lookupAny(clazz);
    }
    if (osc != null) {
      suid = osc.getSerialVersionUID();
    }

    _cacheMisses.incrementAndGet();

    /**
     * To update the tree, this class uses a unique SessionId and results in using a unique
     * Transaction context unrelated to the application context. Therefore if an application does
     * this:
     *
     * <pre>
     * <code>
     * txn.begin();
     * value.put(new SomeClass());
     * txn.rollback();
     * txn.end();
     * </code>
     * </pre>
     *
     * the class SomeClass will be registered even though the enclosing transaction rolled back.
     * This is important because other concurrent threads may have started using the handle for
     * SomeClass. Therefore this class ensures that a non-nested transaction to insert the new
     * ClassInfo into the system volume has committed before adding the handle to the hash table.
     */
    synchronized (this) {
      final SessionId saveSessionId = _persistit.getSessionId();
      Exchange ex = null;
      try {
        _persistit.setSessionId(_sessionId);
        ex = getExchange();
        final Transaction txn = ex.getTransaction();
        final ClassInfo ci;
        final int handle;
        txn.begin();
        ex.clear().append(BY_NAME).append(clazz.getName()).append(suid).fetch();
        final Value value = ex.getValue();
        try {
          if (value.isDefined()) {
            value.setStreamMode(true);

            handle = value.getInt();
            final String storedName = value.getString();
            final long storedSuid = value.getLong();

            if (storedSuid != suid || !clazz.getName().equals(storedName)) {
              throw new ConversionException(
                  "Class "
                      + clazz.getName()
                      + " persistent SUID="
                      + storedSuid
                      + " does not match current class SUID="
                      + suid);
            }
            ci = new ClassInfo(clazz, suid, handle, osc);
          } else {
            //
            // Store a new ClassInfo record
            //
            ex.clear().append(NEXT_ID).fetch();
            handle = Math.max(_testIdFloor, value.isDefined() ? value.getInt() : HANDLE_BASE) + 1;
            value.clear().put(handle);
            ex.store();

            value.clear();
            value.setStreamMode(true);
            value.put(handle);
            value.put(clazz.getName());
            value.put(suid);

            ex.clear().append(BY_NAME).append(clazz.getName()).append(suid).store();

            ex.clear().append(BY_HANDLE).append(handle).store();

            ci = new ClassInfo(clazz, suid, handle, osc);
          }
          txn.commit();
          hashClassInfo(ci);
          return ci;
        } finally {
          txn.end();
        }
      } catch (final PersistitException pe) {
        throw new ConversionException(pe);
      } finally {
        if (ex != null) {
          releaseExchange(ex);
        }
        _persistit.setSessionId(saveSessionId);
      }
    }
  }
Пример #4
0
  @Test
  public void test() throws Exception {
    XmlLoader.load(new FileInputStream("test/test.xml"));

    for (int i = 0; i < Rekord.getTableCount(); i++) {
      System.out.println(Rekord.getTable(i));
    }

    Transaction trans = Rekord.getTransaction();
    trans.start();

    /* INHERITANCE 1 LEVEL * /
    		Group g = new Group();
    		g.setName( "name#1" );
    		g.setPassword( "password#1" );
    		g.save();

    		g.setPassword( "passsword#2" );
    		g.save();

    		g.setName( "name#2" );
    		g.save();

    		g.delete();
    /**/

    /* INHERITANCE 2 LEVEL */
    CommentableGroup cg = new CommentableGroup();
    cg.setName("name#3");
    cg.setPassword("password#3");
    cg.save();

    cg.getCommentable().setCount(4);
    cg.setPassword("password#4");
    cg.save();
    /**/

    /* JOINING */

    SelectQuery<CommentableGroup> q =
        Select.build(CommentableGroup.TABLE, CommentableGroup.TABLE.getLoadProfileAll());

    //		SelectQuery<CommentableGroup> q = Select.from( CommentableGroup.TABLE );
    //
    //		TableAlias commentableGroup = q.getTableAlias();
    //		TableAlias group = q.alias( Group.TABLE );
    //		TableAlias rolePlayer = q.alias( RolePlayer.TABLE );
    //
    //		Join groupJoin = q.join( Join.INNER, group );
    //		groupJoin.where( Group.ROLE_PLAYER_ID ).eq( commentableGroup.alias(
    // CommentableGroup.GROUP_ID ) );
    //
    //		Join rolePlayerJoin = q.join( Join.INNER, rolePlayer );
    //		rolePlayerJoin.where( RolePlayer.ID ).eq( group.alias( Group.ROLE_PLAYER_ID ) );
    //
    //		q.select( commentableGroup.alias( CommentableGroup.COMMENTABLE_ID ) );
    //		q.select( group.alias( Group.PASSWORD ) );
    //		q.select( rolePlayer.alias( RolePlayer.NAME ) );

    System.out.println(q.create().list());
    /**/

    //		long uid0 = new SelectQuery<Model>( User.TABLE ).create().withOffset( 0 ).first( User.ID );
    //		long uid1 = new SelectQuery<Model>( User.TABLE ).create().withOffset( 1 ).first( User.ID );

    /* CRAZY (return-on-save, always-update, out, last-modified-columns) * /
    		Crazy c = new Crazy();
    		c.setDiameter( 4.5f );
    		c.save();
    		System.out.println( c );

    		Thread.sleep( 1000 );

    		c.setDiameter( 3.5f );
    		c.save();
    		System.out.println( c );

    		/* throws a ConcurrentModificationException * /
    		c.setLastModifiedTimestamp( new Timestamp( System.currentTimeMillis() - 10000 ) );
    		c.setDiameter( 2.5f );
    		c.save();

    /**/

    /* UPDATING (history table) * /
    		User u = User.byId( User.Load.ALL, uid0 );
    		u.setName( "New Name!" );
    		u.save();
    /**/

    /* DELETING * /
    		User u = User.byId( User.Load.SHORT_NAME, uid0 );
    		System.out.println( u.getName() );
    		System.out.println( u.exists() );
    		u.delete();
    		System.out.println( u.exists() );

    		User u1 = User.byId( User.Load.ALL, uid1 );
    		System.out.println( u1.getState() );
    		u1.getCommentsBy().clear();
    		u1.save();
    /**/

    //		User u1 = User.byId( User.Load.ALL, uid0 );
    //		System.out.println( u1 );

    //		User u = new User();
    //		u.setName( "lowercase" );
    //		u.save();

    //		User u = User.byId( User.Load.ID, uid1 );
    //		System.out.println( u );
    //		System.out.println( u.getCommentsBy() );
    //		System.out.println( u );

    /* NativeQuery * /
    		Query<User> nq = User.Queries.CREATED_BEFORE.create();
    		nq.bind( "date", User.CREATED_TIMESTAMP, new Timestamp( System.currentTimeMillis() ) );

    		System.out.println( nq.getReadableQuery() );

    		String name = nq.first( User.NAME );
            System.out.println( name );

            List<User> users = nq.list();

            System.out.println( users );

            User u = users.get( 0 );

            trans.start();

            Query<User> us = User.Queries.UPDATE_STATE.create();
            us.bind( u );
            us.bind( "new_state", User.STATE, UserState.REGISTERED );
            us.executeUpdate();
    /**/

    /*SelectQuery #1 * /
    		SelectQuery<Comment> numberOfComments = new SelectQuery<Comment>( Comment.TABLE );
    		numberOfComments.count().where( Comment.USER_ID ).eq( User.ID );

    		SelectQuery<User> query = new SelectQuery<User>( User.TABLE );
    		query.select( User.Load.ALL );
    		query.where( User.COMMENTABLE ).eqExp( "?cid" )
    			  .and( User.NAME ).eq( "LOWERCASE" )
    			  .and( User.CREATED_TIMESTAMP ).between( new Timestamp( System.currentTimeMillis() - 10000000000L ), new Timestamp( System.currentTimeMillis() ) )
    		      .and( numberOfComments ).gt( 0 );

    		System.out.println( query.create().bind( "cid", 5L ).list() );
    /**/

    /*SelectQuery #2* /
    		Condition c_user = is( Comment.USER_ID ).eq( User.ID );

            SelectQuery<Comment> numberOfComments = new SelectQuery<Comment>( Comment.TABLE ).count().where( c_user );

    		Timestamp t0 = new Timestamp( System.currentTimeMillis() - 10000000000L );
    		Timestamp t1 = new Timestamp( System.currentTimeMillis() );

            SelectQuery<User> query = new SelectQuery<User>( User.TABLE );
            query.select( User.Load.ALL );
            query.where(
                is( User.COMMENTABLE ).eqExp( "?cid" ),
                isString( User.NAME ).ieq( "clickerMONKEY" ),
                is( User.CREATED_TIMESTAMP ).between( t0, t1 ),
                is( numberOfComments ).gt( 0 ),
                or(
                    is( User.ID ).gt( 0L ),
                    is( User.ID ).lt( 0L )
                )
            );

            System.out.println( query.create().bind( "cid", 3L ).list() );
    /**/

    //        System.out.println( Select.all( Commentable.TABLE, Commentable.ID ) );

    //        System.out.println( Select.byUnique( User.TABLE, User.ID, 4L ) );

    trans.end(false);
    trans.close();
  }