Search in sources :

Example 1 with ConnectionSource

use of com.j256.ormlite.support.ConnectionSource in project ormlite-android by j256.

the class OrmLiteSqliteOpenHelper method onUpgrade.

/**
	 * Satisfies the {@link SQLiteOpenHelper#onUpgrade(SQLiteDatabase, int, int)} interface method.
	 */
@Override
public final void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ConnectionSource cs = getConnectionSource();
    /*
		 * The method is called by Android database helper's get-database calls when Android detects that we need to
		 * create or update the database. So we have to use the database argument and save a connection to it on the
		 * AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource().
		 */
    DatabaseConnection conn = cs.getSpecialConnection(null);
    boolean clearSpecial = false;
    if (conn == null) {
        conn = new AndroidDatabaseConnection(db, true, cancelQueriesEnabled);
        try {
            cs.saveSpecialConnection(conn);
            clearSpecial = true;
        } catch (SQLException e) {
            throw new IllegalStateException("Could not save special connection", e);
        }
    }
    try {
        onUpgrade(db, cs, oldVersion, newVersion);
    } finally {
        if (clearSpecial) {
            cs.clearSpecialConnection(conn);
        }
    }
}
Also used : SQLException(java.sql.SQLException) AndroidConnectionSource(com.j256.ormlite.android.AndroidConnectionSource) ConnectionSource(com.j256.ormlite.support.ConnectionSource) AndroidDatabaseConnection(com.j256.ormlite.android.AndroidDatabaseConnection) AndroidDatabaseConnection(com.j256.ormlite.android.AndroidDatabaseConnection) DatabaseConnection(com.j256.ormlite.support.DatabaseConnection)

Example 2 with ConnectionSource

use of com.j256.ormlite.support.ConnectionSource in project IPK-BrAPI-Validator by plantbreeding.

the class AppServletContextListener method createDatabaseConnection.

private static void createDatabaseConnection(ServletContext servletContext) {
    String path = Config.get("dbpath");
    String databaseUrl = path;
    ConnectionSource connectionSource;
    try {
        connectionSource = new JdbcPooledConnectionSource(databaseUrl);
        ((JdbcPooledConnectionSource) connectionSource).setUsername(Config.get("dbuser"));
        ((JdbcPooledConnectionSource) connectionSource).setPassword(Config.get("dbpass"));
        if (connectionSource.getDatabaseType().getClass().equals(com.j256.ormlite.db.OracleDatabaseType.class)) {
            Cache.addToCache("dbType", "oracle");
        } else {
            Cache.addToCache("dbType", "other");
        }
        DataSourceManager.setConnectionSource(connectionSource);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
Also used : SQLException(java.sql.SQLException) JdbcPooledConnectionSource(com.j256.ormlite.jdbc.JdbcPooledConnectionSource) ConnectionSource(com.j256.ormlite.support.ConnectionSource) JdbcPooledConnectionSource(com.j256.ormlite.jdbc.JdbcPooledConnectionSource)

Example 3 with ConnectionSource

use of com.j256.ormlite.support.ConnectionSource in project robospice by stephanenicolas.

the class InDatabaseObjectPersister method saveAllForeignObjectsToCache.

/**
 * During this operation, we must save a new POJO (parent) into the database. The problem is
 * that is the POJO contains children POJOs, then saving the parent would not work as the parent
 * must exist in the database prior to saving the children. SO :
 * <ul>
 * <li>we copy the children into memory,
 * <li>put the children to null on parent
 * <li>save the parent to the database
 * <li>if saving filled the parent with previous children, we remove them
 * <li>re inject the children into the parent
 * <li>save the children (as the parent now exists in database).
 * </ul>
 *
 * @param data the parent POJO to save in the database.
 * @throws SQLException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <E> void saveAllForeignObjectsToCache(E data) throws SQLException, IllegalAccessException, InvocationTargetException {
    // copy children on memory
    // set children to null on parents so that we can save the parent
    // without cascade
    Map<Field, Collection<?>> mapFieldToCollection = new HashMap<Field, Collection<?>>();
    Class<? extends Object> parentClass = data.getClass();
    for (Field field : parentClass.getDeclaredFields()) {
        ForeignCollectionField annotation = field.getAnnotation(ForeignCollectionField.class);
        if (annotation != null) {
            Collection<?> collectionCopy = new ArrayList();
            Method getMethod = DatabaseFieldConfig.findGetMethod(field, true);
            Collection collectionInObject = (Collection<?>) getMethod.invoke(data);
            if (collectionInObject != null) {
                collectionCopy.addAll(collectionInObject);
            }
            Method setMethod = DatabaseFieldConfig.findSetMethod(field, true);
            setMethod.invoke(data, (Object) null);
            mapFieldToCollection.put(field, collectionCopy);
        }
    }
    // save parents without cascade
    databaseHelper.createOrUpdateInDatabase(data, (Class<E>) parentClass);
    // get the child from a previous database record
    databaseHelper.refreshFromDatabase(data, (Class<E>) parentClass);
    // collection field of the parent
    for (Field field : parentClass.getDeclaredFields()) {
        if (field.getAnnotation(ForeignCollectionField.class) != null) {
            Method getMethod = DatabaseFieldConfig.findGetMethod(field, true);
            Collection collectionInObject = (Collection<?>) getMethod.invoke(data);
            // lazy collection are not loaded from database, so we load them
            if (collectionInObject instanceof LazyForeignCollection) {
                ((LazyForeignCollection) collectionInObject).refreshCollection();
            }
            ParameterizedType listType = (ParameterizedType) field.getGenericType();
            Class<?> itemInListClass = (Class<?>) listType.getActualTypeArguments()[0];
            databaseHelper.deleteFromDataBase(collectionInObject, itemInListClass);
        }
    }
    // we now saved the parent and can fill the foreign key of the children
    for (Map.Entry<Field, Collection<?>> entry : mapFieldToCollection.entrySet()) {
        Collection<?> collection = entry.getValue();
        // re-set complete children to the parent
        ConnectionSource connectionSource = databaseHelper.getConnectionSource();
        for (Object object : collection) {
            DatabaseTableConfig childDatabaseTableConfig = DatabaseTableConfig.fromClass(connectionSource, object.getClass());
            for (FieldType childFieldType : childDatabaseTableConfig.getFieldTypes(null)) {
                if (parentClass.equals(childFieldType.getType()) && childFieldType.isForeign()) {
                    childFieldType.assignField(object, data, true, null);
                }
            }
            // save children recursively
            saveAllForeignObjectsToCache(object);
        }
    }
    // notify
    if (mapHandledClassesToNotificationUri != null && mapHandledClassesToNotificationUri.containsKey(parentClass)) {
        Uri notificationUri = mapHandledClassesToNotificationUri.get(parentClass);
        if (notificationUri != null) {
            getApplication().getContentResolver().notifyChange(notificationUri, null);
            Object id = getIdField(data.getClass()).extractJavaFieldValue(data);
            Uri itemNotificationUri = notificationUri.buildUpon().appendPath(id.toString()).build();
            getApplication().getContentResolver().notifyChange(itemNotificationUri, null);
        }
    }
// future hook
}
Also used : ForeignCollectionField(com.j256.ormlite.field.ForeignCollectionField) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) Uri(android.net.Uri) FieldType(com.j256.ormlite.field.FieldType) ParameterizedType(java.lang.reflect.ParameterizedType) ForeignCollectionField(com.j256.ormlite.field.ForeignCollectionField) Field(java.lang.reflect.Field) LazyForeignCollection(com.j256.ormlite.dao.LazyForeignCollection) ConnectionSource(com.j256.ormlite.support.ConnectionSource) Collection(java.util.Collection) LazyForeignCollection(com.j256.ormlite.dao.LazyForeignCollection) HashMap(java.util.HashMap) Map(java.util.Map) DatabaseTableConfig(com.j256.ormlite.table.DatabaseTableConfig)

Example 4 with ConnectionSource

use of com.j256.ormlite.support.ConnectionSource in project ormlite-android by j256.

the class DatabaseTableConfigUtil method fromClass.

/**
	 * Build our list table config from a class using some annotation fu around.
	 */
public static <T> DatabaseTableConfig<T> fromClass(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {
    DatabaseType databaseType = connectionSource.getDatabaseType();
    String tableName = DatabaseTableConfig.extractTableName(clazz);
    List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>();
    for (Class<?> classWalk = clazz; classWalk != null; classWalk = classWalk.getSuperclass()) {
        for (Field field : classWalk.getDeclaredFields()) {
            DatabaseFieldConfig config = configFromField(databaseType, tableName, field);
            if (config != null && config.isPersisted()) {
                fieldConfigs.add(config);
            }
        }
    }
    if (fieldConfigs.size() == 0) {
        return null;
    } else {
        return new DatabaseTableConfig<T>(clazz, tableName, fieldConfigs);
    }
}
Also used : DatabaseField(com.j256.ormlite.field.DatabaseField) Field(java.lang.reflect.Field) DatabaseType(com.j256.ormlite.db.DatabaseType) ArrayList(java.util.ArrayList) DatabaseFieldConfig(com.j256.ormlite.field.DatabaseFieldConfig) DatabaseTableConfig(com.j256.ormlite.table.DatabaseTableConfig)

Example 5 with ConnectionSource

use of com.j256.ormlite.support.ConnectionSource in project ormlite-android by j256.

the class OrmLiteSqliteOpenHelper method onCreate.

/**
	 * Satisfies the {@link SQLiteOpenHelper#onCreate(SQLiteDatabase)} interface method.
	 */
@Override
public final void onCreate(SQLiteDatabase db) {
    ConnectionSource cs = getConnectionSource();
    /*
		 * The method is called by Android database helper's get-database calls when Android detects that we need to
		 * create or update the database. So we have to use the database argument and save a connection to it on the
		 * AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource().
		 */
    DatabaseConnection conn = cs.getSpecialConnection(null);
    boolean clearSpecial = false;
    if (conn == null) {
        conn = new AndroidDatabaseConnection(db, true, cancelQueriesEnabled);
        try {
            cs.saveSpecialConnection(conn);
            clearSpecial = true;
        } catch (SQLException e) {
            throw new IllegalStateException("Could not save special connection", e);
        }
    }
    try {
        onCreate(db, cs);
    } finally {
        if (clearSpecial) {
            cs.clearSpecialConnection(conn);
        }
    }
}
Also used : SQLException(java.sql.SQLException) AndroidConnectionSource(com.j256.ormlite.android.AndroidConnectionSource) ConnectionSource(com.j256.ormlite.support.ConnectionSource) AndroidDatabaseConnection(com.j256.ormlite.android.AndroidDatabaseConnection) AndroidDatabaseConnection(com.j256.ormlite.android.AndroidDatabaseConnection) DatabaseConnection(com.j256.ormlite.support.DatabaseConnection)

Aggregations

ConnectionSource (com.j256.ormlite.support.ConnectionSource)4 SQLException (java.sql.SQLException)3 AndroidConnectionSource (com.j256.ormlite.android.AndroidConnectionSource)2 AndroidDatabaseConnection (com.j256.ormlite.android.AndroidDatabaseConnection)2 DatabaseConnection (com.j256.ormlite.support.DatabaseConnection)2 DatabaseTableConfig (com.j256.ormlite.table.DatabaseTableConfig)2 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2 Uri (android.net.Uri)1 LazyForeignCollection (com.j256.ormlite.dao.LazyForeignCollection)1 DatabaseType (com.j256.ormlite.db.DatabaseType)1 DatabaseField (com.j256.ormlite.field.DatabaseField)1 DatabaseFieldConfig (com.j256.ormlite.field.DatabaseFieldConfig)1 FieldType (com.j256.ormlite.field.FieldType)1 ForeignCollectionField (com.j256.ormlite.field.ForeignCollectionField)1 JdbcPooledConnectionSource (com.j256.ormlite.jdbc.JdbcPooledConnectionSource)1 Method (java.lang.reflect.Method)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1