com.j256.ormlite.dao.Dao Java Examples

The following examples show how to use com.j256.ormlite.dao.Dao. 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: DateStringTypeTest.java    From ormlite-core with 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 #2
Source File: QueryBuilderTest.java    From ormlite-core with 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 #3
Source File: BaseMappedQueryTest.java    From ormlite-core with 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 File: DatabaseHelper.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #5
Source File: JdbcQueryBuilderTest.java    From ormlite-jdbc with 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 #6
Source File: DatabaseHelper.java    From android-overlay-protection with 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 #7
Source File: AbstractDao.java    From privacy-friendly-shopping-list with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: EnumIntegerTypeTest.java    From ormlite-core with 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 #9
Source File: JdbcQueryBuilderTest.java    From ormlite-jdbc with 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 #10
Source File: MappedCreateTest.java    From ormlite-core with 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 #11
Source File: DatabaseHelper.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: DatabaseHelper.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #13
Source File: UpdateBuilderTest.java    From ormlite-core with 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 #14
Source File: JdbcDatabaseConnectionTest.java    From ormlite-jdbc with 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 #15
Source File: BigDecimalNumericTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testBigDecimal() throws Exception {
	Class<LocalBigDecimalNumeric> clazz = LocalBigDecimalNumeric.class;
	Dao<LocalBigDecimalNumeric, Object> dao = createDao(clazz, true);
	BigDecimal val = new BigDecimal("1.345345435345345345345345345345345345345345346356524234234");
	String valStr = val.toString();
	LocalBigDecimalNumeric foo = new LocalBigDecimalNumeric();
	foo.bigDecimal = val;
	assertEquals(1, dao.create(foo));
	testType(dao, foo, clazz, val, val, val, valStr, DataType.BIG_DECIMAL_NUMERIC, BIGDECIMAL_COLUMN, false, false,
			false, false, false, false, true, false);
}
 
Example #16
Source File: JdbcQueryBuilderTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Test
public void testMissingAnd() throws Exception {
	Dao<Foo, String> fooDao = createTestData();
	QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
	qb.where().eq(Foo.ID_COLUMN_NAME, foo1.id).eq(Foo.ID_COLUMN_NAME, foo1.id);
	try {
		fooDao.query(qb.prepare());
		fail("expected exception");
	} catch (IllegalStateException e) {
		// expected
	}
}
 
Example #17
Source File: MappedCreateTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testReadOnly() throws Exception {
	Dao<ReadOnly, Integer> readOnlyDao = createDao(ReadOnly.class, true);
	Dao<ReadOnlyInsert, Integer> readOnlyInsertDao = createDao(ReadOnlyInsert.class, true);

	ReadOnly readOnly = new ReadOnly();
	readOnly.stuff = "fpweojfew";
	readOnly.readOnly = "read read and only read";
	assertEquals(1, readOnlyDao.create(readOnly));

	ReadOnly result = readOnlyDao.queryForId(readOnly.id);
	assertNotNull(result);
	assertEquals(readOnly.id, result.id);
	assertEquals(readOnly.stuff, result.stuff);
	// this is null because the above create didn't insert it
	assertNull(result.readOnly);

	ReadOnlyInsert insert = new ReadOnlyInsert();
	insert.stuff = "wefewerwrwe";
	insert.readOnly = "insert should work here";
	assertEquals(1, readOnlyInsertDao.create(insert));

	result = readOnlyDao.queryForId(insert.id);
	assertNotNull(result);
	assertEquals(insert.id, result.id);
	assertEquals(insert.stuff, result.stuff);
	// but this is not null because it was inserted using readOnlyInsertDao
	assertEquals(insert.readOnly, result.readOnly);

	ReadOnly update = result;
	update.readOnly = "something else";
	// the update should _not_ update read-only field
	assertEquals(1, readOnlyDao.update(update));

	result = readOnlyDao.queryForId(insert.id);
	assertFalse(update.readOnly.equals(result.readOnly));
}
 
Example #18
Source File: DaoUtils.java    From poetry with Apache License 2.0 5 votes vote down vote up
/**
 * Create an index for a specific column.
 *
 * @param dao the Dao to execute the query for
 * @param columnName the column to create the index for
 * @param indexName the name of the index to create
 * @throws java.sql.SQLException when the query fails to run
 */
public static void createIndex(Dao<?, ?> dao, String columnName, String indexName) throws java.sql.SQLException
{
    String query = String.format("CREATE INDEX %s ON %s (%s)",
        indexName,
        OrmliteReflection.getTableName(new AnnotationRetriever(), dao.getDataClass()),
        columnName);

    executeQuery(dao, query);
}
 
Example #19
Source File: ORMLiteIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSaveForeignField_thenOk() throws SQLException, IOException {
    Library library = new Library();
    library.setName("My Library");
    library.setAddress(new Address("Main Street nr 20"));
    libraryDao.create(library);

    Dao<Address, Long> addressDao = DaoManager.createDao(connectionSource, Address.class);
    assertEquals(1, addressDao.queryForEq("addressLine", "Main Street nr 20")
        .size());
}
 
Example #20
Source File: JsonTestCase.java    From poetry with Apache License 2.0 5 votes vote down vote up
public void testJsonMapper() throws Exception
  {
      DatabaseHelper helper = DatabaseHelper.getHelper(getContext());

      // Load JSON
      JSONObject json = JsonLoader.loadObject(getContext(), R.raw.test);

      // Get child arrays from JSON
      JSONArray users_json = JsonPathResolver.resolveArray(json, "users");
      JSONArray groups_json = JsonPathResolver.resolveArray(json, "groups");

      // Persist arrays to database
      JsonPersister persister = new JsonPersister(helper.getWritableDatabase());
      persister.persistArray(User.class, users_json);
persister.persistArray(Group.class, groups_json);

      Dao<User, Integer> user_dao = helper.getDao(User.class);
Dao<Group, Integer> group_dao = helper.getDao(Group.class);

List<User> users = user_dao.queryForAll();
      assertEquals(2, users.size());

      List<Group> groups = group_dao.queryForAll();
      assertEquals(3, groups.size());

      User user = user_dao.queryForId(1);
      assertNotNull(user);
      assertEquals("John", user.getName());
      assertEquals(2, user.getTags().size());
      assertEquals("tag2", user.getTags().get(1));

      Group group = group_dao.queryForId(2);
      assertNotNull(group);
      assertEquals("Group B", group.getName());

      DatabaseHelper.releaseHelper();
  }
 
Example #21
Source File: QueryBuilderTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testLeftJoinTwoColumns() throws Exception {
	Dao<Foo, Integer> fooDao = createDao(Foo.class, true);
	Dao<StringColumnArg, Integer> scaDao = createDao(StringColumnArg.class, true);

	Foo foo1 = new Foo();
	foo1.val = 123213213;
	foo1.stringField = "stuff";
	fooDao.create(foo1);

	StringColumnArg sca1 = new StringColumnArg();
	sca1.str1 = foo1.stringField;
	scaDao.create(sca1);

	StringColumnArg sca2 = new StringColumnArg();
	sca2.str1 = "something eles";
	scaDao.create(sca2);

	QueryBuilder<Foo, Integer> fooQb = fooDao.queryBuilder();
	QueryBuilder<StringColumnArg, Integer> scaQb = scaDao.queryBuilder();
	scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb);
	List<StringColumnArg> results = scaQb.query();
	assertNotNull(results);
	assertEquals(1, results.size());
	assertEquals(sca1.id, results.get(0).id);

	scaQb.reset();
	scaQb.join(StringColumnArg.STR1_FIELD, Foo.STRING_COLUMN_NAME, fooQb, JoinType.LEFT, JoinWhereOperation.AND);
	results = scaQb.query();
	assertNotNull(results);
	assertEquals(2, results.size());
	assertEquals(sca1.id, results.get(0).id);
	assertEquals(sca2.id, results.get(1).id);
}
 
Example #22
Source File: DatabaseHelper.java    From AndroidDatabaseLibraryComparison with MIT License 5 votes vote down vote up
/**
 * Returns the Database Access Object (DAO) for our Contact class
 */
public Dao<Contact, Integer> getContactDao() throws SQLException {
    if (contactDao == null) {
        contactDao = getDao(Contact.class);
    }
    return contactDao;
}
 
Example #23
Source File: ByteArrayTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testByteArrayNull() throws Exception {
	Class<LocalByteArray> clazz = LocalByteArray.class;
	Dao<LocalByteArray, Object> dao = createDao(clazz, true);
	LocalByteArray foo = new LocalByteArray();
	assertEquals(1, dao.create(new LocalByteArray()));
	testType(dao, foo, clazz, null, null, null, null, DataType.BYTE_ARRAY, BYTE_COLUMN, false, true, true, false,
			true, false, true, false);
}
 
Example #24
Source File: DateStringTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testDateStringFormat() throws Exception {
	Dao<DateStringFormat, Object> dao = createDao(DateStringFormat.class, true);
	DateStringFormat dateStringFormat = new DateStringFormat();
	dateStringFormat.date = new SimpleDateFormat("yyyy-MM-dd").parse("2012-09-01");
	assertEquals(1, dao.create(dateStringFormat));

	List<DateStringFormat> results = dao.queryForAll();
	assertEquals(1, results.size());
	assertEquals(dateStringFormat.date, results.get(0).date);
}
 
Example #25
Source File: FieldTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testDefaultValueEmptyStringPersist() throws Exception {
	Dao<DefaultEmptyString, Integer> dao = createDao(DefaultEmptyString.class, true);

	DefaultEmptyString foo = new DefaultEmptyString();
	assertEquals(1, dao.create(foo));

	DefaultEmptyString result = dao.queryForId(foo.id);
	assertNotNull(result);
	assertEquals("", result.defaultBlank);
}
 
Example #26
Source File: CharTypeTest.java    From ormlite-core with ISC License 5 votes vote down vote up
@Test
public void testChar() throws Exception {
	Class<LocalChar> clazz = LocalChar.class;
	Dao<LocalChar, Object> dao = createDao(clazz, true);
	char val = 'w';
	String valStr = Character.toString(val);
	LocalChar foo = new LocalChar();
	foo.charField = val;
	assertEquals(1, dao.create(foo));
	testType(dao, foo, clazz, val, val, val, valStr, DataType.CHAR, CHAR_COLUMN, false, true, true, true, false,
			false, true, false);
}
 
Example #27
Source File: KADataService.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public Topic getRootTopic() {
  	Topic topic = null;
try {
	Dao<Topic, String> topicDao = helper.getTopicDao();
	PreparedQuery<Topic> q = topicDao.queryBuilder().where().isNull("parentTopic_id").prepare();
	topic = topicDao.queryForFirst(q);
} catch (SQLException e) {
	e.printStackTrace();
}
return topic;
  }
 
Example #28
Source File: JdbcQueryBuilderTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Test
public void testJoinDoubleWhere() throws Exception {
	Dao<Bar, Integer> barDao = createDao(Bar.class, true);
	Dao<Baz, Integer> bazDao = createDao(Baz.class, true);

	Bar bar1 = new Bar();
	bar1.val = 2234;
	assertEquals(1, barDao.create(bar1));
	Bar bar2 = new Bar();
	bar2.val = 324322234;
	assertEquals(1, barDao.create(bar2));

	Baz baz1 = new Baz();
	baz1.bar = bar1;
	assertEquals(1, bazDao.create(baz1));
	Baz baz2 = new Baz();
	// both have bar1
	baz2.bar = bar1;
	assertEquals(1, bazDao.create(baz2));

	QueryBuilder<Bar, Integer> barQb = barDao.queryBuilder();
	barQb.where().eq(Bar.VAL_FIELD, bar1.val);
	QueryBuilder<Baz, Integer> bazQb = bazDao.queryBuilder();
	bazQb.where().eq(Baz.ID_FIELD, baz1.id);
	List<Baz> results = bazQb.join(barQb).query();
	assertNotNull(results);
	assertEquals(1, results.size());
	assertEquals(bar1.id, results.get(0).bar.id);
}
 
Example #29
Source File: UuidTypeTest.java    From ormlite-core with 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 #30
Source File: TableUtils.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Return an list of SQL statements that need to be run to create a table. To do the work of creating, you should
 * call {@link #createTable}.
 * 
 * @param connectionSource
 *            Our connect source which is used to get the database type, not to apply the creates.
 * @param tableConfig
 *            Hand or spring wired table configuration. If null then the class must have {@link DatabaseField}
 *            annotations.
 * @return The list of table create statements.
 */
public static <T, ID> List<String> getCreateTableStatements(ConnectionSource connectionSource,
		DatabaseTableConfig<T> tableConfig) throws SQLException {
	Dao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig);
	DatabaseType databaseType = connectionSource.getDatabaseType();
	if (dao instanceof BaseDaoImpl<?, ?>) {
		return addCreateTableStatements(databaseType, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), false, false);
	} else {
		tableConfig.extractFieldTypes(databaseType);
		TableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);
		return addCreateTableStatements(databaseType, tableInfo, false, false);
	}
}