com.j256.ormlite.dao.DaoManager Java Examples

The following examples show how to use com.j256.ormlite.dao.DaoManager. 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: JdbcPooledConnectionSourceTest.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
@Test
public void testConnectionRollback() throws Exception {
	JdbcPooledConnectionSource pooled = new JdbcPooledConnectionSource(DEFAULT_DATABASE_URL);
	Dao<Foo, Integer> dao = null;
	DatabaseConnection conn = null;
	try {
		TableUtils.createTable(pooled, Foo.class);
		dao = DaoManager.createDao(pooled, Foo.class);
		conn = dao.startThreadConnection();
		dao.setAutoCommit(conn, false);
		Foo foo = new Foo();
		assertEquals(1, dao.create(foo));
		assertNotNull(dao.queryForId(foo.id));
		dao.endThreadConnection(conn);
		assertNull(dao.queryForId(foo.id));
	} finally {
		TableUtils.dropTable(pooled, Foo.class, true);
		if (dao != null) {
			dao.endThreadConnection(conn);
		}
		pooled.close();
	}
}
 
Example #2
Source File: ManyToManyMain.java    From ormlite-jdbc with ISC License 6 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	/**
	 * Create our DAOs. One for each class and associated table.
	 */
	userDao = DaoManager.createDao(connectionSource, User.class);
	postDao = DaoManager.createDao(connectionSource, Post.class);
	userPostDao = DaoManager.createDao(connectionSource, UserPost.class);

	/**
	 * Create the tables for our example. This would not be necessary if the tables already existed.
	 */
	TableUtils.createTable(connectionSource, User.class);
	TableUtils.createTable(connectionSource, Post.class);
	TableUtils.createTable(connectionSource, UserPost.class);
}
 
Example #3
Source File: GeoPackageTableCreator.java    From geopackage-core-java with MIT License 6 votes vote down vote up
/**
 * Create the minimum required GeoPackage tables
 */
public void createRequired() {

	// Create the Spatial Reference System table (spec Requirement 10)
	createSpatialReferenceSystem();

	// Create the Contents table (spec Requirement 13)
	createContents();

	// Create the required Spatial Reference Systems (spec Requirement
	// 11)
	try {
		SpatialReferenceSystemDao dao = DaoManager.createDao(
				db.getConnectionSource(), SpatialReferenceSystem.class);
		dao.createWgs84();
		dao.createUndefinedCartesian();
		dao.createUndefinedGeographic();
	} catch (SQLException e) {
		throw new GeoPackageException(
				"Error creating default required Spatial Reference Systems",
				e);
	}
}
 
Example #4
Source File: DBEmailQueueTest.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTimeZone() throws SQLException {
  // create a temporary H2 connection
  JdbcConnectionSource connection = new JdbcConnectionSource("jdbc:h2:mem:");
  TableUtils.createTable(connection, DBEmailQueue.class);
  Dao<DBEmailQueue, Integer> dao = DaoManager.createDao(connection, DBEmailQueue.class);

  DBEmailQueue email = DBEmailQueue.makeInvitation("[email protected]", "[email protected]", "pw");
  dao.create(email);

  // Force a daylight savings time string in the DB
  setRawDate(connection, email.getId(), "2013-05-17T14:47:59.864022");
  Date t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-05-17T14:47:59.864Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1368802079864L, t.getTime());

  // Set a date/time in standard time, not daylight time
  setRawDate(connection, email.getId(), "2013-11-04T15:38:11.997012");
  t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-11-04T15:38:11.997Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1383579491997L, t.getTime());
}
 
Example #5
Source File: LocalSqliteDriverImpl.java    From mae-annotation with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setupDatabase(ConnectionSource source) throws MaeDBException {

    try {
        taskDao = DaoManager.createDao(source, Task.class);
        charIndexDao = DaoManager.createDao(source, CharIndex.class);
        tagTypeDao = DaoManager.createDao(source, TagType.class);
        eTagDao = DaoManager.createDao(source, ExtentTag.class);
        lTagDao = DaoManager.createDao(source, LinkTag.class);
        attTypeDao = DaoManager.createDao(source, AttributeType.class);
        attDao = DaoManager.createDao(source, Attribute.class);
        argTypeDao = DaoManager.createDao(source, ArgumentType.class);
        argDao = DaoManager.createDao(source, Argument.class);
    } catch (SQLException e) {
        throw catchSQLException(e);
    }

    charIndexQuery = charIndexDao.queryBuilder();
    tagTypeQuery = tagTypeDao.queryBuilder();
    eTagQuery = eTagDao.queryBuilder();
    lTagQuery = lTagDao.queryBuilder();
    attTypeQuery = attTypeDao.queryBuilder();
    attQuery = attDao.queryBuilder();
    argTypeQuery = argTypeDao.queryBuilder();
    argQuery = argDao.queryBuilder();

    allDaos = new Dao[]{ taskDao, charIndexDao, tagTypeDao, eTagDao, lTagDao, attTypeDao, attDao, argTypeDao, argDao};
    allQueryBuilders = new QueryBuilder[]{ charIndexQuery, tagTypeQuery, eTagQuery, lTagQuery, attTypeQuery, attQuery, argTypeQuery, argQuery};

    dropAllTables(source);
    createAllTables(source);

}
 
Example #6
Source File: DataPersisterMain.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	/*
	 * We register our own persister for DateTime objects. ORMLite actually has a built in one but it has to use
	 * reflection.
	 */
	DataPersisterManager.registerDataPersisters(DateTimePersister.getSingleton());

	userDao = DaoManager.createDao(connectionSource, User.class);

	// if you need to create the table
	TableUtils.createTable(connectionSource, User.class);
}
 
Example #7
Source File: ForeignMain.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	accountDao = DaoManager.createDao(connectionSource, Account.class);
	orderDao = DaoManager.createDao(connectionSource, Order.class);

	// if you need to create the table
	TableUtils.createTable(connectionSource, Account.class);
	TableUtils.createTable(connectionSource, Order.class);
}
 
Example #8
Source File: ForeignCollectionMain.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	accountDao = DaoManager.createDao(connectionSource, Account.class);
	orderDao = DaoManager.createDao(connectionSource, Order.class);

	// if you need to create the table
	TableUtils.createTable(connectionSource, Account.class);
	TableUtils.createTable(connectionSource, Order.class);
}
 
Example #9
Source File: FieldConfigMain.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	DatabaseType databaseType = connectionSource.getDatabaseType();
	DatabaseTableConfig<Account> accountTableConfig = buildAccountTableConfig(databaseType);
	accountDao = DaoManager.createDao(connectionSource, accountTableConfig);

	DatabaseTableConfig<Delivery> deliveryTableConfig = buildDeliveryTableConfig(databaseType, accountTableConfig);
	deliveryDao = DaoManager.createDao(connectionSource, deliveryTableConfig);

	// if you need to create the table
	TableUtils.createTable(connectionSource, accountTableConfig);
	TableUtils.createTable(connectionSource, deliveryTableConfig);
}
 
Example #10
Source File: ExtentTagTest.java    From mae-annotation with GNU General Public License v3.0 5 votes vote down vote up
protected void setupDatabase(ConnectionSource source) throws Exception {
    eTagDao = DaoManager.createDao(source, ExtentTag.class);
    tagTypeDao = DaoManager.createDao(source, TagType.class);
    attTypeDao = DaoManager.createDao(source, AttributeType.class);
    attDao = DaoManager.createDao(source, Attribute.class);
    charIndexDao = DaoManager.createDao(source, CharIndex.class);

    lTagDao = DaoManager.createDao(source, LinkTag.class);
    argTypeDao = DaoManager.createDao(source, ArgumentType.class);
    argDao = DaoManager.createDao(source, Argument.class);

    dropAllTables(source);

    TableUtils.createTable(source, CharIndex.class);
    TableUtils.createTable(source, ExtentTag.class);
    TableUtils.createTable(source, TagType.class);
    TableUtils.createTable(source, AttributeType.class);
    TableUtils.createTable(source, Attribute.class);

    TableUtils.createTable(source, LinkTag.class);
    TableUtils.createTable(source, ArgumentType.class);
    TableUtils.createTable(source, Argument.class);

    noun = new TagType("NOUN", "N", false);
    verb = new TagType("VERB", "V", false);
    tagTypeDao.create(noun);
    tagTypeDao.create(verb);

}
 
Example #11
Source File: ContentsDao.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * Get or create a Tile Matrix Set DAO
 * 
 * @return tile matrix set dao
 * @throws SQLException
 *             upon dao creation failure
 */
private TileMatrixSetDao getTileMatrixSetDao() throws SQLException {
	if (tileMatrixSetDao == null) {
		tileMatrixSetDao = DaoManager.createDao(connectionSource,
				TileMatrixSet.class);
	}
	return tileMatrixSetDao;
}
 
Example #12
Source File: ContentsDao.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * Get or create a Geometry Columns DAO
 * 
 * @return geometry columns dao
 * @throws SQLException
 *             upon dao creation failure
 */
private GeometryColumnsDao getGeometryColumnsDao() throws SQLException {
	if (geometryColumnsDao == null) {
		geometryColumnsDao = DaoManager.createDao(connectionSource,
				GeometryColumns.class);
	}
	return geometryColumnsDao;
}
 
Example #13
Source File: GeoPackageCoreImpl.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T, S extends BaseDaoImpl<T, ?>> S createDao(Class<T> type) {
	S dao;
	try {
		dao = DaoManager.createDao(database.getConnectionSource(), type);
	} catch (SQLException e) {
		throw new GeoPackageException(
				"Failed to create " + type.getSimpleName() + " dao", e);
	}
	return dao;
}
 
Example #14
Source File: GeoPackageDaoManager.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * Unregister the provided
 * 
 * @param connectionSource
 *            connection source
 * @param clazz
 *            DAO class type
 */
public static void unregisterDao(ConnectionSource connectionSource,
		Class<?> clazz) {

	Dao<?, ?> dao = DaoManager.lookupDao(connectionSource, clazz);
	if (dao != null) {
		DaoManager.unregisterDao(connectionSource, dao);
	}

}
 
Example #15
Source File: DataColumnConstraintsDao.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * Get or create a Data Columns DAO
 * 
 * @return data columns dao
 * @throws SQLException
 */
private DataColumnsDao getDataColumnsDao() throws SQLException {
	if (dataColumnsDao == null) {
		dataColumnsDao = DaoManager.createDao(connectionSource,
				DataColumns.class);
	}
	return dataColumnsDao;
}
 
Example #16
Source File: TableIndexDao.java    From geopackage-core-java with MIT License 5 votes vote down vote up
/**
 * Get or create a Geometry Index DAO
 * 
 * @return geometry index dao
 * @throws SQLException
 */
private GeometryIndexDao getGeometryIndexDao() throws SQLException {
	if (geometryIndexDao == null) {
		geometryIndexDao = DaoManager.createDao(connectionSource,
				GeometryIndex.class);
	}
	return geometryIndexDao;
}
 
Example #17
Source File: FeatureInfoBuilder.java    From geopackage-android-map with MIT License 5 votes vote down vote up
/**
 * Project the geometry into the provided projection
 *
 * @param geometryData geometry data
 * @param projection   projection
 */
public void projectGeometry(GeoPackageGeometryData geometryData, Projection projection) {

    if (geometryData.getGeometry() != null) {

        try {
            SpatialReferenceSystemDao srsDao = DaoManager.createDao(featureDao.getDb().getConnectionSource(), SpatialReferenceSystem.class);
            int srsId = geometryData.getSrsId();
            SpatialReferenceSystem srs = srsDao.queryForId((long) srsId);

            if (!projection.equals(srs.getOrganization(), srs.getOrganizationCoordsysId())) {

                Projection geomProjection = srs.getProjection();
                ProjectionTransform transform = geomProjection.getTransformation(projection);

                Geometry projectedGeometry = transform.transform(geometryData.getGeometry());
                geometryData.setGeometry(projectedGeometry);
                SpatialReferenceSystem projectionSrs = srsDao.getOrCreateCode(projection.getAuthority(), Long.parseLong(projection.getCode()));
                geometryData.setSrsId((int) projectionSrs.getSrsId());
            }
        } catch (SQLException e) {
            throw new GeoPackageException("Failed to project geometry to projection with Authority: "
                    + projection.getAuthority() + ", Code: " + projection.getCode(), e);
        }
    }

}
 
Example #18
Source File: SimpleMain.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * Setup our database and DAOs
 */
private void setupDatabase(ConnectionSource connectionSource) throws Exception {

	accountDao = DaoManager.createDao(connectionSource, Account.class);

	// if you need to create the table
	TableUtils.createTable(connectionSource, Account.class);
}
 
Example #19
Source File: BaseJdbcTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@Before
public void before() throws Exception {
	DaoManager.clearCache();
	if (connectionSource != null) {
		return;
	}
	// do this for everyone
	System.setProperty("derby.stream.error.file", "target/derby.log");
	setDatabaseParams();
	doOpenConnectionSource();
}
 
Example #20
Source File: BaseJdbcTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
@After
public void after() throws Exception {
	if (connectionSource != null) {
		for (Class<?> clazz : dropClassSet) {
			dropTable(clazz, true);
		}
		dropClassSet.clear();
		for (DatabaseTableConfig<?> tableConfig : dropTableConfigSet) {
			dropTable(tableConfig, true);
		}
		dropTableConfigSet.clear();
	}
	closeConnectionSource();
	DaoManager.clearCache();
}
 
Example #21
Source File: BaseJdbcTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
protected <T, ID> Dao<T, ID> createDao(Class<T> clazz, boolean createTable) throws Exception {
	if (connectionSource == null) {
		throw new SQLException(DATASOURCE_ERROR);
	}
	@SuppressWarnings("unchecked")
	BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, clazz);
	return configDao(dao, createTable);
}
 
Example #22
Source File: BaseJdbcTest.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
protected <T, ID> Dao<T, ID> createDao(DatabaseTableConfig<T> tableConfig, boolean createTable) throws Exception {
	if (connectionSource == null) {
		throw new SQLException(DATASOURCE_ERROR);
	}
	@SuppressWarnings("unchecked")
	BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, tableConfig);
	return configDao(dao, createTable);
}
 
Example #23
Source File: ORMLiteIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setup() throws SQLException {
    connectionSource = new JdbcPooledConnectionSource("jdbc:h2:mem:myDb");
    TableUtils.createTableIfNotExists(connectionSource, Library.class);
    TableUtils.createTableIfNotExists(connectionSource, Address.class);
    TableUtils.createTableIfNotExists(connectionSource, Book.class);

    libraryDao = DaoManager.createDao(connectionSource, Library.class);

    bookDao = DaoManager.createDao(connectionSource, Book.class);
}
 
Example #24
Source File: ORMLiteIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCustomDao_whenSave_thenOk() throws SQLException, IOException {
    Library library = new Library();
    library.setName("My Library");

    LibraryDao customLibraryDao = DaoManager.createDao(connectionSource, Library.class);
    customLibraryDao.create(library);
    assertEquals(1, customLibraryDao.findByName("My Library")
        .size());
}
 
Example #25
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 #26
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);
	}
}
 
Example #27
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 #28
Source File: BaseCoreTest.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * @throws Exception
 *             For sub-classes.
 */
@Before
public void before() throws Exception {
	connectionSource = new WrappedConnectionSource(new H2ConnectionSource());
	databaseType = connectionSource.getDatabaseType();
	DaoManager.clearCache();
}
 
Example #29
Source File: BaseCoreTest.java    From ormlite-core with ISC License 5 votes vote down vote up
protected <T, ID> Dao<T, ID> createDao(Class<T> clazz, boolean createTable) throws SQLException {
	if (connectionSource == null) {
		throw new SQLException("Connection source is null");
	}
	@SuppressWarnings("unchecked")
	BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, clazz);
	return configDao(dao, createTable);
}
 
Example #30
Source File: BaseCoreTest.java    From ormlite-core with ISC License 5 votes vote down vote up
protected <T, ID> Dao<T, ID> createDao(DatabaseTableConfig<T> tableConfig, boolean createTable)
		throws SQLException {
	if (connectionSource == null) {
		throw new SQLException("Connection source is null");
	}
	@SuppressWarnings("unchecked")
	BaseDaoImpl<T, ID> dao = (BaseDaoImpl<T, ID>) DaoManager.createDao(connectionSource, tableConfig);
	return configDao(dao, createTable);
}