Medical Nerds Blog Logo
medicalnerds.com

technology, stats and IT for medics

 

Executing raw SQL with WebObjects and Project Wonder

March 6th, 2010 by Mark · No Comments

WebObjects is an extraordinarily powerful java based web-application server. On occasions, I need to execute arbitrary SQL against the underlying database. This is not necessary for most uses, but for certain batch operations it is useful.

I’m currently writing an introduction to WebObjects and I hope to post these introductory documents both here and to the WebObjects wiki

To execute arbitrary SQL without getting any results back (e.g. executing non-Select SQL statements) use ERXEOAccessUtilities.evaluateRawSqlForEntity()

For example:


	protected static void deleteCache() {
		ERXEOAccessUtilities.evaluateSQLWithEntityNamed(ERXEC.newEditingContext(), "CachedParentConcepts", "truncate t_cached_parent_concepts;");
	}

Deletes all the rows in the table t_cached_parent_concepts

If you wish to get the results back from a custom SQL query and convert the raw rows into enterprise objects, use EOUtilities.rawRowsForSQL

For example:


	/**
	 * Helper function to execute raw SQL and convert the results to enterprise objects
	 * @param ec
	 * @param entityName
	 * @param sql
	 * @param columns
	 * @return
	 */
	public static NSArray executeRawSqlToEO(EOEditingContext ec, String entityName, String sql, NSArray columns) {
		NSArray gids = executeRawSql(ec, entityName, sql, columns);
		return ERXEOGlobalIDUtilities.fetchObjectsWithGlobalIDs(ec, gids);
	}
	
	/**
	 * Executes a raw SQL statement returning an array of EOGlobalIDs.
	 * The raw SQL should return sufficient columns to allow the raw row to be converted into an
	 * enterprise object.
	 * You will usually need to convert column names to attribute names to allow the raw rows
	 * to be converted properly.
	 * 
	 * @param ec - editing context
	 * @param entityName - name of the entity that the raw rows will be converted to
	 * @param sql - the raw SQL statement to be executed
	 * @param columns - array of attribute names to replace the column names that will arrive from the database
	 * @return
	 */
	public static NSArray executeRawSql(EOEditingContext ec, String entityName, String sql, NSArray columns) {
		NSMutableArray gids = new NSMutableArray();
		EOModelGroup modelGroup = ERXEOAccessUtilities.modelGroup(ec);
		EOEntity entity = modelGroup.entityNamed(entityName);
		String modelName = entity.model().name();
		NSArray> rawRows = EOUtilities.rawRowsForSQL(ec, modelName, sql, columns);
		for(NSDictionary row : rawRows) {
			EOGlobalID gid = entity.globalIDForRow(row);
			if (gid==null) throw new NullPointerException("Could not fetch global ID for raw row: " + row);
			gids.add(gid);
		}
		return gids;		
	}
	

Tags: WebObjects

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment

(Don't forget to fill in the Captcha)

CAPTCHA image