com.j256.ormlite.misc.TransactionManager Java Examples

The following examples show how to use com.j256.ormlite.misc.TransactionManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DatabaseHelper.java    From XMPPSample_Studio with Apache License 2.0 6 votes vote down vote up
public void updateContact(final ContactItem contact) {
    try {
        TransactionManager.callInTransaction(getConnectionSource(),
                new Callable<Void>() {
                    public Void call() throws Exception {
                        List<ContactItem> contacts = DatabaseHelper.this
                                .getDao(ContactItem.class).queryForEq(
                                        "username", contact.username);
                        if (contacts != null)
                            DatabaseHelper.this.getDao(ContactItem.class)
                                    .createOrUpdate(contact);
                        return null;
                    }
                });
        return;
    } catch (SQLException localSQLException) {
        localSQLException.printStackTrace();
    }
}
 
Example #2
Source File: DatabaseHelper.java    From XMPPSample_Studio with Apache License 2.0 6 votes vote down vote up
public void updateContactStatus(final String jid, final String status,
                                final int mood) {
    try {
        TransactionManager.callInTransaction(getConnectionSource(),
                new Callable<Void>() {
                    public Void call() throws Exception {

                        UpdateBuilder<ContactItem, ?> builder = getDao(
                                ContactItem.class).updateBuilder();
                        builder.updateColumnValue("status", status);
                        builder.updateColumnValue("mood", mood);
                        builder.where().eq("username",
                                JidCreate.bareFrom(jid));
                        getDao(ContactItem.class).update(builder.prepare());

                        return (Void) null;
                    }
                });
        return;
    } catch (SQLException localSQLException) {
        localSQLException.printStackTrace();
    }
}
 
Example #3
Source File: DatabaseHelper.java    From XMPPSample_Studio with Apache License 2.0 6 votes vote down vote up
public void updateContacts(final Collection<ContactItem> contactList) {
    if (contactList == null || contactList.size() == 0)
        return;
    try {
        TransactionManager.callInTransaction(getConnectionSource(),
                new Callable<Void>() {
                    public Void call() throws Exception {
                        Dao<ContactItem, ?> localDao = DatabaseHelper.this
                                .getDao(ContactItem.class);
                        for (ContactItem contact : contactList) {
                            localDao.createOrUpdate(contact);
                        }
                        return null;
                    }
                });
        return;
    } catch (SQLException localSQLException) {
        localSQLException.printStackTrace();
    }
}
 
Example #4
Source File: Message.java    From zulip-android with Apache License 2.0 6 votes vote down vote up
public static void createMessages(final ZulipApp app,
                                  final List<Message> messages) {
    try {
        TransactionManager.callInTransaction(app.getDatabaseHelper()
                .getConnectionSource(), new Callable<Void>() {
            public Void call() throws Exception {
                RuntimeExceptionDao<Message, Object> messageDao = app.getDao(Message.class);

                for (Message m : messages) {
                    Person person = Person.getOrUpdate(app, m.getSenderEmail(), m.getSenderFullName(), m.getAvatarUrl(), m.getSenderId());
                    m.setSender(person);
                    Stream stream = null;
                    if (m.getType() == MessageType.STREAM_MESSAGE) {
                        stream = Stream.getByName(app, m.getRecipients());
                    }
                    m.setStream(stream);
                    messageDao.createOrUpdate(m);
                }
                return null;
            }
        });
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: ZulipApp.java    From zulip-android with Apache License 2.0 6 votes vote down vote up
/**
 * Fills the Emoji Table with the existing emoticons saved in the assets folder.
 */
private void setupEmoji() {
    try {
        final RuntimeExceptionDao<Emoji, Object> dao = getDao(Emoji.class);
        if (dao.queryForAll().size() != 0) return;
        final String emojis[] = getAssets().list("emoji");
        TransactionManager.callInTransaction(getDatabaseHelper()
                        .getConnectionSource(),
                new Callable<Void>() {
                    public Void call() throws Exception {
                        for (String newEmoji : emojis) {
                            //currently emojis are in png format
                            newEmoji = newEmoji.replace(".png", "");
                            dao.create(new Emoji(newEmoji));
                        }
                        return null;
                    }
                });
    } catch (SQLException | IOException e) {
        ZLog.logException(e);
    }
}
 
Example #6
Source File: SimpleMain.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
/**
 * Example of created a query with a ? argument using the {@link SelectArg} object. You then can set the value of
 * this object at a later time.
 */
private void useTransactions(ConnectionSource connectionSource) throws Exception {
	String name = "trans1";
	final Account account = new Account(name);
	assertEquals(1, accountDao.create(account));

	TransactionManager transactionManager = new TransactionManager(connectionSource);
	try {
		// try something in a transaction
		transactionManager.callInTransaction(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				// we do the delete
				assertEquals(1, accountDao.delete(account));
				assertNull(accountDao.queryForId(account.getId()));
				// but then (as an example) we throw an exception which rolls back the delete
				throw new Exception("We throw to roll back!!");
			}
		});
		fail("This should have thrown");
	} catch (SQLException e) {
		// expected
	}

	assertNotNull(accountDao.queryForId(account.getId()));
}
 
Example #7
Source File: OrmLiteDao.java    From AndroidBase with Apache License 2.0 5 votes vote down vote up
/**
 * 数据批量处理
 *
 * @param list      要处理的数据集合
 * @param batchType 操作类型
 * @return
 */
private boolean doBatchInTransaction(final List<T> list, final int batchType) throws SQLException {
    ConnectionSource connectionSource = ormLiteDao.getConnectionSource();
    TransactionManager transactionManager = new TransactionManager(connectionSource);
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return doBatch(list, batchType);
        }
    };
    return transactionManager.callInTransaction(callable);
}
 
Example #8
Source File: UnsortedTests.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
public void testMessageTrim() throws SQLException {
    prepTests();
    TransactionManager.callInTransaction(app.getDatabaseHelper()
            .getConnectionSource(), new Callable<Void>() {
        public Void call() throws Exception {
            for (int i = 1; i <= 300; i++) {
                sampleMessage(app, i);
            }

            for (int i = 501; i <= 800; i++) {
                sampleMessage(app, i);
            }

            app.getDao(MessageRange.class).create(new MessageRange(1, 300));
            app.getDao(MessageRange.class).create(
                    new MessageRange(501, 800));
            return null;
        }
    });

    RuntimeExceptionDao<MessageRange, Integer> messageRangeDao = app
            .getDao(MessageRange.class);

    assertEquals(600, messageDao.countOf());
    Message.trim(100, app);
    this.messageDao.queryForAll();
    assertEquals(100, messageDao.countOf());
    assertEquals(1, messageRangeDao.countOf());
    MessageRange r = messageRangeDao.queryBuilder().queryForFirst();
    // We have messages 701 through 800, which is 100 messages.
    assertEquals(800, r.high);
    assertEquals(800 - 99, r.low);

}
 
Example #9
Source File: DatabasePhotoEntityStore.java    From photoviewer with Apache License 2.0 5 votes vote down vote up
public void saveAllSynchronous(final Collection<PhotoEntity> entities) throws SQLException {
    TransactionManager.callInTransaction(mPhotosDao.getConnectionSource(),
            () -> {
                for (PhotoEntity photoEntity : entities) {
                    mPhotosDao.createOrUpdate(photoEntity);
                }
                return null;
            });
}
 
Example #10
Source File: StatementExecutorTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testCallBatchTasksNestedInTransaction() throws Exception {
	SpecialConnectionSource cs = new SpecialConnectionSource(new H2ConnectionSource());
	final Dao<Foo, Integer> dao = DaoManager.createDao(cs, Foo.class);
	TableUtils.createTable(cs, Foo.class);
	final Foo foo = new Foo();
	assertEquals(1, dao.create(foo));

	TransactionManager.callInTransaction(cs, new Callable<Void>() {
		@Override
		public Void call() throws Exception {
			dao.callBatchTasks(new Callable<Void>() {
				@Override
				public Void call() throws Exception {
					dao.delete(foo);
					return null;
				}
			});
			return null;
		}
	});

	// make sure the delete happened
	assertNull(dao.queryForId(foo.id));
	// make sure there is no special connection
	assertNull(cs.getSpecialConnection(dao.getTableName()));
}
 
Example #11
Source File: Message.java    From zulip-android with Apache License 2.0 4 votes vote down vote up
public static void trim(final int olderThan, final ZulipApp app) {
    final RuntimeExceptionDao<Message, Integer> messageDao = app
            .<Message, Integer>getDao(Message.class);

    if (messageDao.countOf() <= olderThan) {
        return;
    }

    try {
        synchronized (app.updateRangeLock) {
            TransactionManager.callInTransaction(app.getDatabaseHelper()
                    .getConnectionSource(), new Callable<Void>() {
                public Void call() throws Exception {

                    int topID = messageDao.queryBuilder()
                            .orderBy(Message.ID_FIELD, false)
                            .offset((long) olderThan).limit((long) 1)
                            .queryForFirst().getID();

                    DeleteBuilder<Message, Integer> messageDeleter = messageDao
                            .deleteBuilder();
                    messageDeleter.where().le(ID_FIELD, topID);
                    messageDeleter.delete();

                    MessageRange rng = MessageRange.getRangeContaining(
                            topID,
                            app.<MessageRange, Integer>getDao(MessageRange.class));
                    if (rng == null) {
                        Log.wtf("trim",
                                "Message in database but not in range!");
                        return null;
                    }
                    if (rng.high == topID) {
                        rng.delete();
                    } else {
                        rng.low = topID + 1;
                        rng.update();
                    }
                    DeleteBuilder<MessageRange, Integer> dB2 = app
                            .<MessageRange, Integer>getDao(
                                    MessageRange.class).deleteBuilder();

                    dB2.where().le("high", topID);
                    dB2.delete();

                    return null;
                }
            });
        }
    } catch (SQLException e) {
        ZLog.logException(e);
    }

}
 
Example #12
Source File: MessageRange.java    From zulip-android with Apache License 2.0 4 votes vote down vote up
public static void markRange(ZulipApp app, final int low, final int high) {
    final RuntimeExceptionDao<MessageRange, Integer> messageRangeDao = app
            .getDao(MessageRange.class);
    try {
        synchronized (app.updateRangeLock) {
            TransactionManager.callInTransaction(app.getDatabaseHelper()
                    .getConnectionSource(), new Callable<Void>() {
                public Void call() throws Exception {
                    Where<MessageRange, Integer> where = messageRangeDao
                            .queryBuilder().orderBy("low", true).where();
                    @SuppressWarnings("unchecked")
                    List<MessageRange> ranges = where.or(
                            where.and(where.ge("high", low - 1),
                                    where.le("high", high + 1)),
                            where.and(where.ge("low", low - 1),
                                    where.le("low", high + 1))).query();

                    MessageRange rng = new MessageRange(low, high);
                    if (!ranges.isEmpty()) {
                        Log.i("", "our low: " + rng.low + ", our high: "
                                + rng.high);
                        int dbLow = ranges.get(0).low;
                        int dbHigh = ranges.get(ranges.size() - 1).high;
                        Log.i("", "their low: " + dbLow + ", their high: "
                                + dbHigh);
                        if (dbLow < rng.low) {
                            rng.low = dbLow;
                        }
                        if (dbHigh > rng.high) {
                            rng.high = dbHigh;
                        }
                        messageRangeDao.delete(ranges);
                    }
                    messageRangeDao.createOrUpdate(rng);
                    return null;
                }
            });
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: GeoPackageCoreImpl.java    From geopackage-core-java with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T callInTransaction(Callable<T> callable) throws SQLException {
	return TransactionManager
			.callInTransaction(database.getConnectionSource(), callable);
}