Java Code Examples for com.j256.ormlite.dao.Dao

The following examples show how to use com.j256.ormlite.dao.Dao. These examples are extracted from open source projects. 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 Project: ormlite-core   Source File: UpdateBuilderTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testUpdateBuildUpdateMathod() throws Exception {
	Dao<UpdateDate, Integer> dao = createDao(UpdateDate.class, true);
	UpdateDate updateDate = new UpdateDate();
	updateDate.date = new Date();
	assertEquals(1, dao.create(updateDate));
	Date newDate = new Date(System.currentTimeMillis() + 10);

	UpdateBuilder<UpdateDate, Integer> ub = dao.updateBuilder();
	ub.updateColumnValue(UpdateDate.DATE_FIELD, newDate);
	// this used to cause a NPE because of a missing args
	assertEquals(1, ub.update());
	// make sure the update worked
	UpdateDate result = dao.queryForId(updateDate.id);
	assertNotNull(result);
	assertEquals(newDate, result.date);
}
 
Example 2
Source Project: ormlite-jdbc   Source File: JdbcDatabaseConnectionTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testQueryForLong() throws Exception {
	DatabaseConnection databaseConnection = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	try {
		Dao<Foo, Object> dao = createDao(Foo.class, true);
		Foo foo = new Foo();
		long id = 21321321L;
		foo.id = id;
		assertEquals(1, dao.create(foo));

		StringBuilder sb = new StringBuilder();
		sb.append("select ");
		databaseType.appendEscapedEntityName(sb, "id");
		sb.append(" from foo");
		assertEquals(id, databaseConnection.queryForLong(sb.toString()));
	} finally {
		connectionSource.releaseConnection(databaseConnection);
	}
}
 
Example 3
Source Project: ormlite-core   Source File: BaseMappedQueryTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testMappedQuery() throws Exception {
	Field field = Foo.class.getDeclaredField(Foo.ID_COLUMN_NAME);
	String tableName = "basefoo";
	Dao<Foo, Integer> dao = createDao(Foo.class, false);
	FieldType[] resultFieldTypes =
			new FieldType[] { FieldType.createFieldType(databaseType, tableName, field, Foo.class) };
	BaseMappedQuery<Foo, Integer> baseMappedQuery = new BaseMappedQuery<Foo, Integer>(dao, baseFooTableInfo,
			"select * from " + tableName, new FieldType[0], resultFieldTypes) {
	};
	DatabaseResults results = createMock(DatabaseResults.class);
	int colN = 1;
	expect(results.getObjectCacheForRetrieve()).andReturn(null);
	expect(results.getObjectCacheForStore()).andReturn(null);
	expect(results.findColumn(Foo.ID_COLUMN_NAME)).andReturn(colN);
	int id = 63365;
	expect(results.getInt(colN)).andReturn(id);
	replay(results);
	Foo baseFoo = baseMappedQuery.mapRow(results);
	assertNotNull(baseFoo);
	assertEquals(id, baseFoo.id);
	verify(results);
}
 
Example 4
Source Project: ormlite-core   Source File: MappedCreateTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testGeneratedId() throws Exception {
	TableInfo<GeneratedId, Integer> tableInfo =
			new TableInfo<GeneratedId, Integer>(databaseType, GeneratedId.class);
	Dao<GeneratedId, Integer> dao = createDao(GeneratedId.class, false);
	StatementExecutor<GeneratedId, Integer> se =
			new StatementExecutor<GeneratedId, Integer>(databaseType, tableInfo, dao);
	DatabaseConnection databaseConnection = createMock(DatabaseConnection.class);
	databaseConnection.insert(isA(String.class), isA(Object[].class), isA(FieldType[].class),
			isA(GeneratedKeyHolder.class));
	expectLastCall().andAnswer(new IAnswer<Object>() {
		@Override
		public Integer answer() throws Throwable {
			GeneratedKeyHolder keyHolder = (GeneratedKeyHolder) (getCurrentArguments()[3]);
			keyHolder.addKey(2);
			return 1;
		}
	});
	replay(databaseConnection);
	GeneratedId genIdSeq = new GeneratedId();
	se.create(databaseConnection, genIdSeq, null);
	verify(databaseConnection);
}
 
Example 5
Source Project: ormlite-jdbc   Source File: JdbcQueryBuilderTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testLimitDoublePrepare() throws Exception {
	Dao<Foo, String> fooDao = createTestData();
	QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
	// no limit the default
	List<Foo> results = fooDao.query(qb.prepare());
	assertEquals(2, results.size());
	assertEquals(foo1, results.get(0));
	assertEquals(foo2, results.get(1));
	qb.limit(1L);
	results = fooDao.query(qb.prepare());
	assertEquals(1, results.size());
	assertEquals(foo1, results.get(0));
	results = fooDao.query(qb.prepare());
	assertEquals(1, results.size());
	assertEquals(foo1, results.get(0));
}
 
Example 6
Source Project: ormlite-core   Source File: EnumIntegerTypeTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testEnumIntResultsNoFieldType() throws Exception {
	Class<LocalEnumInt> clazz = LocalEnumInt.class;
	Dao<LocalEnumInt, Object> dao = createDao(clazz, true);
	OurEnum val = OurEnum.SECOND;
	LocalEnumInt foo = new LocalEnumInt();
	foo.ourEnum = val;
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = conn.compileStatement("select * from " + TABLE_NAME, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, true);
		DatabaseResults results = stmt.runQuery(null);
		assertTrue(results.next());
		assertEquals(val.ordinal(), DataType.ENUM_INTEGER.getDataPersister().resultToJava(null, results,
				results.findColumn(ENUM_COLUMN)));
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 7
Source Project: android-overlay-protection   Source File: DatabaseHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
 * the various data to match the new version number.
 */
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        Log.i(TAG, "onUpgrade");
        TableUtils.dropTable(connectionSource, SuspectedApp.class, true);
        Log.d(TAG, String.format("Dropped suspected app table!"));
        Dao<WhiteEntry, Integer> whiteListDao = getWhiteListDao();
        DeleteBuilder<WhiteEntry, Integer> deleteBuilder = whiteListDao.deleteBuilder();
        deleteBuilder.where().eq("systemEntry", Boolean.TRUE);
        int deleted = deleteBuilder.delete();
        Log.d(TAG, String.format("Delete %d old system whitelist entries", deleted));
        onCreate(db, connectionSource);
    } catch (SQLException e) {
        Log.e(TAG, "Can't drop databases", e);
        throw new RuntimeException(e);
    }
}
 
Example 8
Source Project: ormlite-jdbc   Source File: JdbcQueryBuilderTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testLimitAfterSelect() throws Exception {
	Dao<Foo, String> fooDao = createTestData();
	QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
	// no limit the default
	List<Foo> results = fooDao.query(qb.prepare());
	assertEquals(2, results.size());
	assertEquals(foo1, results.get(0));
	assertEquals(foo2, results.get(1));
	qb.limit(1L);
	results = fooDao.query(qb.prepare());
	assertEquals(1, results.size());
	assertEquals(foo1, results.get(0));
	// set back to no-limit
	qb.limit(null);
	results = fooDao.query(qb.prepare());
	assertEquals(2, results.size());
	assertEquals(foo1, results.get(0));
	assertEquals(foo2, results.get(1));
}
 
Example 9
Source Project: ormlite-core   Source File: QueryBuilderTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testOrderByRaw() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo1 = new Foo();
	foo1.val = 1;
	foo1.equal = 10;
	assertEquals(1, dao.create(foo1));
	Foo foo2 = new Foo();
	foo2.val = 5;
	foo2.equal = 7;
	assertEquals(1, dao.create(foo2));
	List<Foo> results = dao.queryBuilder()
			.orderByRaw("(" + Foo.VAL_COLUMN_NAME + "+" + Foo.EQUAL_COLUMN_NAME + ") DESC")
			.query();
	assertEquals(2, results.size());
	assertEquals(foo2.id, results.get(0).id);
	assertEquals(foo1.id, results.get(1).id);
}
 
Example 10
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
    try {
        Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
        List<TempTarget> tempTargets;
        QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        Where where = queryBuilder.where();
        where.ge("date", mills);
        PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
        tempTargets = daoTempTargets.query(preparedQuery);
        return tempTargets;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<TempTarget>();
}
 
Example 11
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long mills, boolean ascending) {
    try {
        Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
        List<ProfileSwitch> profileSwitches;
        QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        queryBuilder.limit(100L);
        Where where = queryBuilder.where();
        where.ge("date", mills);
        PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
        profileSwitches = daoProfileSwitch.query(preparedQuery);
        return profileSwitches;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<>();
}
 
Example 12
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
    try {
        Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
        List<ProfileSwitch> profileSwitches;
        QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
        queryBuilder.orderBy("date", ascending);
        queryBuilder.limit(100L);
        Where where = queryBuilder.where();
        where.between("date", from, to);
        PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
        profileSwitches = daoProfileSwitch.query(preparedQuery);
        return profileSwitches;
    } catch (SQLException e) {
        log.error("Unhandled exception", e);
    }
    return new ArrayList<>();
}
 
Example 13
protected Long saveOrUpdate(T entity)
{
    try
    {
        @SuppressWarnings("unchecked")
        Dao<T, Long> dao = database.getDao((Class) entity.getClass());
        dao.createOrUpdate(entity);
        PFALogger.debug(getClass().getName(), SAVE_OR_UPDATE, SUCCESSFUL);
        return entity.getId();
    }
    catch ( SQLException e )
    {
        PFALogger.error(getClass().getName(), SAVE_OR_UPDATE + ENTITY + entity.toString(), e);
        return null;
    }
}
 
Example 14
Source Project: ormlite-core   Source File: DateStringTypeTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testDateStringResultInvalid() throws Exception {
	Class<LocalString> clazz = LocalString.class;
	Dao<LocalString, Object> dao = createDao(clazz, true);
	LocalString foo = new LocalString();
	foo.string = "not a date format";
	assertEquals(1, dao.create(foo));
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(FOO_TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = conn.compileStatement("select * from " + TABLE_NAME, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, true);
		DatabaseResults results = stmt.runQuery(null);
		assertTrue(results.next());
		int colNum = results.findColumn(STRING_COLUMN);
		DataType.DATE_STRING.getDataPersister().resultToJava(null, results, colNum);
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		connectionSource.releaseConnection(conn);
	}
}
 
Example 15
Source Project: ormlite-core   Source File: UuidTypeTest.java    License: ISC License 5 votes vote down vote up
@Test(expected = SQLException.class)
public void testUuidInvalidDefault() throws Exception {
	Dao<UuidClassInvalidDefault, Object> dao = createDao(UuidClassInvalidDefault.class, true);
	UuidClassInvalidDefault foo = new UuidClassInvalidDefault();
	dao.create(foo);

	assertNull(foo.uuid);
	dao.refresh(foo);
}
 
Example 16
Source Project: renrenpay-android   Source File: UserDao.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean delete(int id) {
        try {
            Dao<User, Integer> dao = DatabaseHelper.getDbHelper().getDao(User.class);
            return dao.deleteById(id) > 0;
        } catch(SQLException e) {
//            ExceptionUtils.report(e);
            e.printStackTrace();
            return false;
        }
    }
 
Example 17
Source Project: renrenpay-android   Source File: UserDao.java    License: Apache License 2.0 5 votes vote down vote up
public static User findById(int id) {
    User user = null;
    try {
        Dao<User, Integer> dao = DatabaseHelper.getDbHelper().getDao(User.class);
        user = dao.queryForId(id);
    } catch(SQLException e) {
        e.printStackTrace();
    }
    return user;
}
 
Example 18
Source Project: ormlite-core   Source File: FieldType.java    License: ISC License 5 votes vote down vote up
/**
 * Create a shell object and assign its id field.
 */
private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache)
		throws SQLException {
	@SuppressWarnings("unchecked")
	Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;
	FT foreignObject = castDao.createObjectInstance();
	foreignIdField.assignField(connectionSource, foreignObject, val, false, objectCache);
	return foreignObject;
}
 
Example 19
Source Project: AndroidDatabaseLibraryComparison   Source File: DatabaseHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the Database Access Object (DAO) for our AddressItem class
 */
public Dao<AddressItem, Integer> getAddressItemDao() throws SQLException {
    if (addressItemDao == null) {
        addressItemDao = getDao(AddressItem.class);
    }
    return addressItemDao;
}
 
Example 20
Source Project: FamilyChat   Source File: ShortVideoDao.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Dao<ShortVideoBean, Integer> getDao()
{
    if (mHelper == null || !mHelper.isOpen())
    {
        mHelper = null;
        mHelper = DbOpenHelper.getInstance(FCApplication.getInstance());
    }
    return mHelper.getDao(ShortVideoBean.class);
}
 
Example 21
Source Project: PacketProxy   Source File: Database.java    License: Apache License 2.0 5 votes vote down vote up
public <T,ID> Dao<T, ID> createTable(Class<T> c, Observer observer) throws Exception
{
	addObserver(observer);
	TableUtils.createTableIfNotExists(source, c);
	Dao<T, ID> dao = DaoManager.createDao(source, c);
	return dao;
}
 
Example 22
Source Project: ormlite-core   Source File: SelectIteratorTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testFirstCurrent() throws Exception {
	Dao<Foo, Integer> dao = createDao(Foo.class, true);
	Foo foo = new Foo();
	assertEquals(1, dao.create(foo));

	CloseableIterator<Foo> iterator = dao.iterator();
	try {
		assertEquals(foo, iterator.current());
		assertFalse(iterator.hasNext());
		assertNull(iterator.current());
	} finally {
		iterator.close();
	}
}
 
Example 23
Source Project: ormlite-core   Source File: DateIntegerTypeTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testDateIntegerSeconds() throws Exception {
	Dao<LocalDateInteger, Object> dao = createDao(LocalDateInteger.class, true);
	long now = System.currentTimeMillis();
	Date val = new Date(now - (now % 1000) + 1 /* 1 extra ms here */);
	LocalDateInteger foo = new LocalDateInteger();
	foo.date = val;
	assertEquals(1, dao.create(foo));
	List<LocalDateInteger> results = dao.queryForAll();
	assertNotNull(results);
	assertEquals(1, results.size());
	// this is always false because the above date has some millis
	assertFalse(results.get(0).date.equals(val));
	assertEquals(new Date(now - (now % 1000)), results.get(0).date);
}
 
Example 24
Source Project: ormlite-jdbc   Source File: JdbcQueryBuilderTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testDistinct() throws Exception {
	Dao<Foo, String> fooDao = createTestData();
	QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
	qb.distinct().selectColumns(Foo.EQUAL_COLUMN_NAME);
	List<Foo> results = fooDao.query(qb.prepare());
	assertEquals(1, results.size());
	assertEquals(EQUAL_VAL, results.get(0).equal);
	assertNull(results.get(0).id);
}
 
Example 25
Source Project: SightRemote   Source File: DatabaseHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Dao<PumpStatusChanged, Integer> getPumpStatusChangedDao() {
    try {
        if (pumpStatusChangedDao == null) pumpStatusChangedDao = getDao(PumpStatusChanged.class);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return pumpStatusChangedDao;
}
 
Example 26
Source Project: ormlite-core   Source File: ByteObjectTypeTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testByteObj() throws Exception {
	Class<LocalByteObj> clazz = LocalByteObj.class;
	Dao<LocalByteObj, Object> dao = createDao(clazz, true);
	byte val = 123;
	String valStr = Byte.toString(val);
	LocalByteObj foo = new LocalByteObj();
	foo.byteField = val;
	assertEquals(1, dao.create(foo));
	testType(dao, foo, clazz, val, val, val, valStr, DataType.BYTE_OBJ, BYTE_COLUMN, false, true, false, false,
			false, false, true, true);
}
 
Example 27
Source Project: ormlite-core   Source File: DatabaseFieldTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testBaseClassAnnotations() throws Exception {
	Sub sub = new Sub();
	String stuff = "djeqpodjewdopjed";
	sub.stuff = stuff;

	Dao<Sub, Object> dao = createDao(Sub.class, true);
	assertEquals(0, sub.id);
	assertEquals(1, dao.create(sub));
	Sub sub2 = dao.queryForId(sub.id);
	assertNotNull(sub2);
	assertEquals(sub.stuff, sub2.stuff);
}
 
Example 28
Source Project: ormlite-core   Source File: BaseMappedQueryTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testCacheWithSelectColumns() throws Exception {
	Dao<CacheWithSelectColumns, Object> dao = createDao(CacheWithSelectColumns.class, true);
	// Add object to database
	CacheWithSelectColumns foo = new CacheWithSelectColumns();
	foo.text = "some text";
	dao.create(foo);
	// enable object cache
	dao.setObjectCache(true);

	// fetch the object, but only with its id field
	QueryBuilder<CacheWithSelectColumns, Object> qb =
			dao.queryBuilder().selectColumns(CacheWithSelectColumns.COLUMN_NAME_ID);
	CacheWithSelectColumns result = qb.queryForFirst();
	assertNotNull(result);
	assertNull(result.text);

	// fetch the same object again, this time asking for the text column as well
	qb = dao.queryBuilder().selectColumns(CacheWithSelectColumns.COLUMN_NAME_ID,
			CacheWithSelectColumns.COLUMN_NAME_TEXT);
	result = qb.queryForFirst();
	assertNotNull(result);
	assertEquals(foo.text, result.text);

	// fetch the same object again, this time asking for everything
	qb = dao.queryBuilder();
	result = qb.queryForFirst();
	assertNotNull(result);
	assertEquals(foo.text, result.text);
}
 
Example 29
Source Project: ormlite-jdbc   Source File: JdbcQueryBuilderTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testBetweenStrings() throws Exception {
	Dao<Foo, String> fooDao = createTestData();
	QueryBuilder<Foo, String> qb = fooDao.queryBuilder();

	String low = ID_PREFIX;
	String high = ID_PREFIX + "99999";
	qb.where().between(Foo.ID_COLUMN_NAME, low, high);
	List<Foo> results = fooDao.query(qb.prepare());
	assertEquals(2, results.size());
	assertEquals(foo1, results.get(0));
	assertEquals(foo2, results.get(1));
}
 
Example 30
Source Project: ormlite-core   Source File: DataPersisterManagerTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testCustomTypePersister() throws Exception {
	Dao<PersistedStoredPersister, Object> dao = createDao(PersistedStoredPersister.class, true);
	PersistedStoredPersister wrapper = new PersistedStoredPersister();
	String stuff = "pfjwpfjww";
	wrapper.storedClass = new StoredClass(stuff);
	assertEquals(1, dao.create(wrapper));

	PersistedStoredPersister wrapperResult = dao.queryForId(wrapper.id);
	assertNotNull(wrapperResult.storedClass);
	assertEquals(stuff, wrapperResult.storedClass.stuff);
}