![]() |
Spring provides an abstraction for data access via ADO.NET that provides the following benefits and features
This chapter is divided up into a number of sections that describe the major areas of functionality within Spring's ADO.NET support.
There are a variety of motivations to create a higher level ADO.NET persistence API. Encapsulation of common 'boiler plate' tasks when coding directly against the ADO.NET API. For example here is a list of the tasks typically required to be coded for processing a result set query. Note that the code needed when using Spring's ADO.NET framework is in italics.
Spring takes care of the low-level tasks and lets you focus on specifying the SQL and doing the real work of extracting data. This standard boiler plate pattern is encapsulated in a class, AdoTemplate. The name 'Template' is used because if you look at the typical code workflow for the above listing, you would essentially like to 'template' it, that is stick in the code that is doing the real work in the midst of the resource, transaction, exception management. Another very important motivation is to provide an easy means to group multiple ADO.NET operations within a single transaction while at the same time adhering to a DAO style design in which transactions are initiated outside the DAOs, typically in a business service layer. Using the 'raw' ADO.NET API to implement this design often results in explicitly passing around of a Transaction/Connection pair to DAO objects. This infrastructure task distracts from the main database task at hand and is frequently done in an ad-hoc manner. Integrating with Spring's transaction management features provides an elegant means to achieve this common design goal. There are many other benefits to integration with Spring's transaction management features, see Chapter 17, Transaction management for more information. Provider Independent Code: In .NET 1.1 writing provider independent code was difficult for a variety of reasons. The most prominent was the lack of a lack of a central factory for creating interface based references to the core ADO.NET classes such as IDbConnection, IDbCommand, DbParameter etc. In addition, the APIs exposed by many of these interfaces were minimal or incomplete - making for tedious code that would otherwise be more easily developed with provider specific subclasses. Lastly, there was no common base class for data access exceptions across the providers. .NET 2.0 made many changes for the better in that regard across all these areas of concern - and Spring only plugs smaller holes in that regard to help in the portability of your data access code. Resource Management: The 'using' block is the heart of elegant resource management in .NET from the API perspective. However, despite its elegance, writing 2-3 nested using statements for each data access method also starts to be tedious, which introduces the risk of forgetting to do the right thing all the time in terms of both direct coding and 'cut-n-paste' errors. Spring centralizes this resource management in one spot so you never forget or make a mistake and rely on it always being done correctly. Parameter management: Frequently much of data access code is related to creating appropriate parameters. To alleviate this boiler plate code Spring provides a parameter 'builder' class that allows for succinct creation of parameter collections. Also, for the case of stored procedures, parameters can be derived from the database itself which reduces parameter creation code to just one line. Frequently result set data is converted into objects. Spring provides a simple framework to organize that mapping task and allows you to reuse mapping artifacts across your application. Exceptions: The standard course of action when an exception is thrown from ADO.NET code is to look up the error code and then re-run the application to set a break point where the exception occurred so as to see what the command text and data values were that caused the exception. Spring provides exceptions translation from these error codes (across database vendors) to a Data Access Object exception hierarchy. This allows you to quickly understand the category of the error that occurred and also the 'bad' data which lead to the exception. Warnings: A common means to extract warning from the database, and to optionally treat those warnings as a reason to rollback is not directly supported with the new System.Data.Common API Portability: Where possible, increase the portability of code across database provider in the higher level API. The need adding of a parameter prefix, i.e. @ for SqlServer or ':' for oracle is one such example of an area where a higher level API can offer some help in making your code more portable. Note that Spring's ADO.NET framework is just 'slightly' above the raw API. It does not try to compete with other higher level persistence abstractions such as result set mappers (iBATIS.NET) or other ORM tools (NHibernate). (Apologies if your favorite is left out of that short list). As always, pick and choose the appropriate level of abstraction for the task at hand. As a side note, Spring does offer integration with higher level persistence abstractions (currently NHibernate) providing such features as integration with Spring's transaction management features as well as mixing orm/ado.net operations within the same transaction. Before you get started executing queries against the database you need to connect to it. Chapter 19, DbProvider covers this topic in detail so we only discuss the basic idea of how to interact with the database in this section. One important ingredient that increases the portability of writing ADO.NET applications is to refer to the base ADO.NET interfaces, such as IDbCommand or IDbParameter in your code. However, In the .NET 1.1 BCL the only means to obtain references to instances of these interfaces is to directly instantiate the classes, i.e. for SqlServer this would be IDbCommand command = new SqlCommand(); One of the classic creational patterns in the GoF Design Patterns book addresses this situation directly, the Abstract Factory pattern. This approach was applied in the .NET BCL with the introduction of the DbProviderFactory class which contains various factory methods that create the various objects used in ADO.NET programming. In addition, .NET 2.0 introduced new abstract base classes that all ADO.NET providers must inherit from. These base classes provide more core functionality and uniformity across the various providers as compared to the original ADO.NET interfaces. Spring's database provider abstraction has a similar API to that of .ADO.NET 2.0's DbProviderFactory. The central interface is IDbProvider and it has factory methods that are analogous to those in the DbProviderFactory class except that they return references to the base ADO.NET interfaces. Note that in keeping with the Spring Framework's philosophy, IDbProvider is an interface, and can thus be easily mocked or stubbed as necessary. Another key element of this interface is the ConnectionString property that specifies the specific runtime information necessary to connect to the provider. The interface also has a IDbMetadata property that contains minimal database metadata information needed to support the functionality in rest of the Spring ADO.NET framework. It is unlikely you will need to use the DatabaseMetadata class directly in your application. For more information on configuring a Spring database provider refer to Chapter 19, DbProvider Each database vendor is associated with a particular implementation of the IDbProvider interfaces. A variety of implementations are provided with Spring such as SqlServer, Oracle and MySql. Refer to the documentation on Spring's DbProvider for creating a configuration for database that is not yet provided. The programmatic way to create an IDbProvider is shown below IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
Please refer to the Chapter 19, DbProvider for information on how to create a IDbProvider in Spring's XML configuration file. The ADO.NET framework consists of a few namespaces, namely
The The The The Finally the Spring provides two styles to interact with ADO.NET. The first is a
'template' based approach in which you create an single instance of
Generally speaking, experience has shown that the AdoTemplate approach reads very cleanly when looking at DAO method implementation as you can generally see all the details of what is going on as compared to the object based approach. The object based approach however, offers some advantages when calling stored procedures since it acts as a cache of derived stored procedure arguments and can be invoked passing a variable length argument list to the 'execute' method. As always, take a look at both approaches and use the approach that provides you with the most benefit for a particular situation. The class There are two implementations of AdoTemplate adoTemplate = new AdoTemplate(dbProvider);
If you are using the generic version of AdoTemplate you can access the non-generic version via the property ClassicAdoTemplate. The following two sections show basic usage of the
The In this example a simple query against the 'Northwind' database is done to determine the number of customers who have a particular postal code. public int FindCountWithPostalCode(string postalCode) { return adoTemplate.Execute<int>(delegate(DbCommand command) { command.CommandText = "select count(*) from Customers where PostalCode = @PostalCode"; DbParameter p = command.CreateParameter(); p.ParameterName = "@PostalCode"; p.Value = postalCode; command.Parameters.Add(p); return (int)command.ExecuteScalar(); }); } The As you can see, only the most relevant portions of the data access
task at hand need to be coded. (Note that in this simple example you
would be better off using AdoTemplate's ExecuteScalar method directly.
This method is described in the following sections). As mentioned
before, the typical usage scenario for the Execute callback would
involve downcasting the passed in There is also an interface based version of the execute method. The signatures for the delegate and interface are shown below public delegate T CommandDelegate<T>(DbCommand command); public interface ICommandCallback { T DoInCommand<T>(DbCommand command); } While the delegate version offers the most compact syntax, the
interface version allows for reuse. The corresponding method signatures
on public class AdoTemplate : AdoAccessor, IAdoOperations { ... T Execute<T>(ICommandCallback action); T Execute<T>(CommandDelegate<T> del); ... } While it is common for .NET 2.0 ADO.NET provider implementations to inherit from the base class System.Data.Common.DbCommand, that is not a requirement. To accommodate the few that don't, which as of this writing are the latest Oracle (ODP) provider, Postgres, and DB2 for iSeries, two additional execute methods are provided. The only difference is the use of callback and delegate implementations that have IDbCommand and not DbCommand as callback arguments. The following listing shows these methods on AdoTemplate. public class AdoTemplate : AdoAccessor, IAdoOperations { ... T Execute<T>(IDbCommandCallback action); T Execute<T>(IDbCommandDelegate<T> del); ... } where the signatures for the delegate and interface are shown below public delegate T IDbCommandDelegate<T>(IDbCommand command); public interface IDbCommandCallback<T> { T DoInCommand(IDbCommand command); } Internally the Depending on how portable you would like your code to be, you can
choose among the two callback styles. The one based on
>
AdoTemplate differs from its .NET 2.0 generic counterpart in that
it exposes the interface public virtual int FindCountWithPostalCode(string postalCode) { return (int) AdoTemplate.Execute(new PostalCodeCommandCallback(postalCode)); } and the callback implementation is private class PostalCodeCommandCallback : ICommandCallback { private string cmdText = "select count(*) from Customer where PostalCode = @PostalCode"; private string postalCode; public PostalCodeCommandCallback(string postalCode) { this.postalCode = postalCode; } public object DoInCommand(IDbCommand command) { command.CommandText = cmdText; IDbDataParameter p = command.CreateParameter(); p.ParameterName = "@PostalCode"; p.Value = postalCode; command.Parameters.Add(p); return command.ExecuteScalar(); } } Note that in this example, one could more easily use AdoTemplate's ExecuteScalar method. The Execute method has interface and delegate overloads. The signatures for the delegate and interface are shown below public delegate object CommandDelegate(IDbCommand command); public interface ICommandCallback { object DoInCommand(IDbCommand command); } The corresponding method signatures on
public class AdoTemplate : AdoAccessor, IAdoOperations { ... object Execute(CommandDelegate del); object Execute(ICommandCallback action); ... } Note that you have to cast to the appropriate object type returned from the execute method. There are many methods in AdoTemplate so it is easy to feel a bit overwhelmed when taking a look at the SDK documentation. However, after a while you will hopefully find the class 'easy to navigate' with intellisense. Here is a quick categorization of the method names and their associated data access operation. Each method is overloaded to handle common cases of passing in parameter values. The generic 'catch-all' method
The following methods mirror those on the DbCommand object.
Mapping result sets to objects
Mapping result set to a single object
Query with a callback to create the DbCommand object. These are generally used by the framework itself to support other functionality, such as in the Spring.Data.Objects namespace.
DataTable and DataSet operations
Parameter Creation utility methods
In turn each method typically has four overloads, one with no parameters and three for providing parameters. Aside from the DataTable/DataSet operations, the three parameter overloads are of the form shown below
The CallbackInterfaceOrDelegate is one of the three types listed previously. The parameters setting arguments are of the form
The first overload is a convenience method when you only have one parameter to set. The database enumeration is the base class 'Enum' allowing you to pass in any of the provider specific enumerations as well as the common DbType enumeration. This is a trade off of type-safety with provider portability. (Note generic version could be improved to provide type safety...). The second overload contains a collection of parameters. The data type is Spring's IDbParameters collection class discussed in the following section. The third overload is a callback interface allowing you to set the parameters (or other properties) of the IDbCommand passed to you by the framework directly. If you are using .NET 2.0 the delegate versions of the methods are very useful since very compact definitions of database operations can be created that reference variables local to the DAO method. This removes some of the tedium in passing parameters around with interface based versions of the callback functions since they need to be passed into the constructor of the implementing class. The general guideline is to use the delegate when available for functionality that does not need to be shared across multiple DAO classes or methods and use interface based version to reuse the implementation in multiple places. The .NET 2.0 versions make use of generics where appropriate and therefore enhance type-safety. AdoTemplate has the following properties that you can configure
The AdoTemplate is used in conjunction with an implementation of a
To use local transactions, those with only one transactional
resource (i.e. the database) you will typically use
While it is most common to use Spring's transaction management features to avoid the low level management of ADO.NET connection and transaction objects, you can retrieve the connection/transaction pair that was created at the start of a transaction and bound to the current thread. This may be useful for some integration with other data access APIs. The can be done using the utility class ConnectionUtils as shown below. IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
ConnectionTxPair connectionTxPairToUse = ConnectionUtils.GetConnectionTxPair(dbProvider);
IDbCommand command = DbProvider.CreateCommand();
command.Connection = connectionTxPairToUse.Connection;
command.Transaction = connectionTxPairToUse.Transaction;
It is possible to provide a wrapper around the standard .NET provider interfaces such that you can use the plain ADO.NET API in conjunction with Spring's transaction management features. If you are using
AdoTemplate's methods throw exceptions within a Data Access Object (DAO) exception hierarchy described in Chapter 18, DAO support. In addition, the command text and error code of the exception are extracted and logged. This leads to easier to write provider independent exception handling layer since the exceptions thrown are not tied to a specific persistence technology. Additionally, for ADO.NET code the error messages logged provide information on the SQL and error code to better help diagnose the issue. A fair amount of the code in ADO.NET applications is related to the creation and population of parameters. The BCL parameter interfaces are very minimal and do not have many convenience methods found in provider implementations such as SqlClient. Even still, with SqlClient, there is a fair amount of verbosity to creating and populating a parameter collection. Spring provides two ways to make this mundane task easier and more portable across providers. Instead of creating a parameter on one line of code, then setting
its type on another and size on another, a builder and parameter
interface, IDbParametersBuilder builder = CreateDbParametersBuilder(); builder.Create().Name("Country").Type(DbType.String).Size(15).Value(country); builder.Create().Name("City").Type(DbType.String).Size(15).Value(city); // now get the IDbParameters collection for use in passing to AdoTemplate methods. IDbParameters parameters = builder.GetParameters(); Please note that The parameter prefix, i.e. '@' in Sql Server, is not required to be added to the parameter name. The DbProvider is aware of this metadata and AdoTemplate will add it automatically if required before execution. An additional feature of the IDbParametersBuilder is to create a Spring FactoryObject that creates IDbParameters for use in the XML configuration file of the IoC container. By leveraging Spring's expression evaluation language, the above lines of code can be taken as text from the XML configuration file and executed. As a result you can externalize your parameter definitions from your code. In combination with abstract object definitions and importing of configuration files your increase the chances of having one code base support multiple database providers just by a change in configuration files. This class is similar to the parameter collection class you find in provider specific implementations of IDataParameterCollection. It contains a variety of convenience methods to build up a collection of parameters. Here is an abbreviated listing of the common convenience methods.
Here a simple usage example // inside method has has local variable country and city... IDbParameters parameters = CreateDbParameters(); parameters.AddWithValue("Country", country).DbType = DbType.String; parameters.Add("City", DbType.String).Value = city; // now pass on to AdoTemplate methods. The parameter prefix, i.e. '@' in Sql Server, is not required to be added to the parameter name. The DbProvider is aware of this metadata and AdoTemplate will add it automatically if required before execution. While the use of IDbParameters or IDbParametersBuilder will remove the need for use to vendor specific parameter prefixes when creating a parameter collection, @User in Sql SqlSerer vs. :User in Oracle, you still need to specify the vendor specific parameter prefix in the SQL Text. Portable SQL in this regard is possible to implement, it is available as a feature in Spring Java. If you would like such a feature, please raise an issue. The passed in implementation of Spring provides a class to map public interface IDataReaderWrapper : IDataReader { IDataReader WrappedReader { get; set; } } All of AdoTemplates callback interfaces/delegates that have an
Frequently you will use a common mapper for DBNull across your
application so only one instance of The 'ExecuteNonQuery' and 'ExecuteScalar' methods of
ExecuteNonQuery is used to perform create, update, and delete operations. It has four overloads listed below reflecting different ways to set the parameters. An example of using this method is shown below public void CreateCredit(float creditAmount) { AdoTemplate.ExecuteNonQuery(CommandType.Text, String.Format("insert into Credits(creditAmount) VALUES ({0})", creditAmount)); } A common ADO.NET development task is reading in a result set and converting it to a collection of domain objects. The family of QueryWith methods on AdoTemplate help in this task. The responsibility of performing the mapping is given to one of three callback interfaces/delegates that you are responsible for developing. These callback interfaces/delegates are:
There are generic versions of the IResultSetExtractor and IRowMapper interfaces/delegates providing you with additional type-safety as compared to the object based method signatures used in the .NET 1.1 implementation. As usual with callback APIs in Spring.Data, your implementations of these interfaces/delegates are only concerned with the core task at hand - mapping data - while the framework handles iteration of readers and resource management. Each 'QueryWith' method has 4 overloads to handle common ways to bind parameters to the command text. The following sections describe in more detail how to use Spring's lightweight object mapping framework. The ResultSetExtractor gives you control to iterate over the IDataReader returned from the query. You are responsible for iterating through all the result sets and returning a corresponding result object. Implementations of IResultSetExtractor are typically stateless and therefore reusable as long as the implementation doesn't access stateful resources. The framework will close the IDataReader for you. The interface and delegate signature for ResutSetExtractors is shown below for the generic version in the Spring.Data.Generic namespace public interface IResultSetExtractor<T> { T ExtractData(IDataReader reader); } public delegate T ResultSetExtractorDelegate<T>(IDataReader reader); The definition for the non-generic version is shown below public interface IResultSetExtractor { object ExtractData(IDataReader reader); } public delegate object ResultSetExtractorDelegate(IDataReader reader); Here is an example taken from the Spring.DataQuickStart. It is a method in a DAO class that inherits from AdoDaoSupport, which has a convenience method 'CreateDbParametersBuilder()'. public virtual IList<string> GetCustomerNameByCountryAndCityWithParamsBuilder(string country, string city) { IDbParametersBuilder builder = CreateDbParametersBuilder(); builder.Create().Name("Country").Type(DbType.String).Size(15).Value(country); builder.Create().Name("City").Type(DbType.String).Size(15).Value(city); return AdoTemplate.QueryWithResultSetExtractor(CommandType.Text, customerByCountryAndCityCommandText, new CustomerNameResultSetExtractor<List<string>>(), builder.GetParameters()); } The implementation of the ResultSetExtractor is shown below. internal class CustomerNameResultSetExtractor<T> : IResultSetExtractor<T> where T : IList<string>, new() { public T ExtractData(IDataReader reader) { T customerList = new T(); while (reader.Read()) { string contactName = reader.GetString(0); customerList.Add(contactName); } return customerList; } } Internally the implementation of the QueryWithRowCallback and QueryWithRowMapper methods are specializations of the general ResultSetExtractor. For example, the QueryWithRowMapper implementation iterates through the result set, calling the callback method 'MapRow' for each row and collecting the results in an IList. If you have a specific case that is not covered by the QueryWithXXX methods you can subclass AdoTemplate and follow the same implementation pattern to create a new QueryWithXXX method to suit your needs. The RowCallback is usually a stateful object itself or populates another stateful object that is accessible to the calling code. Here is a sample take from the Data QuickStart public class RowCallbackDao : AdoDaoSupport { private string cmdText = "select ContactName, PostalCode from Customers"; public virtual IDictionary<string, IList<string>> GetPostalCodeCustomerMapping() { PostalCodeRowCallback statefullCallback = new PostalCodeRowCallback(); AdoTemplate.QueryWithRowCallback(CommandType.Text, cmdText, statefullCallback); // Do something with results in stateful callback... return statefullCallback.PostalCodeMultimap; } } The PostalCodeRowCallback builds up state which is then retrieved via the property PostalCodeMultimap. The Callback implementation is shown below internal class PostalCodeRowCallback : IRowCallback { private IDictionary<string, IList<string>> postalCodeMultimap = new Dictionary<string, IList<string>>(); public IDictionary<string, IList<string>> PostalCodeMultimap { get { return postalCodeMultimap; } } public void ProcessRow(IDataReader reader) { string contactName = reader.GetString(0); string postalCode = reader.GetString(1); IList<string> contactNameList; if (postalCodeMultimap.ContainsKey(postalCode)) { contactNameList = postalCodeMultimap[postalCode]; } else { postalCodeMultimap.Add(postalCode, contactNameList = new List<string>()); } contactNameList.Add(contactName); } } The RowMapper lets you focus on just the logic to map a row of your result set to an object. The creation of a IList to store the results and iterating through the IDataReader is handled by the framework. Here is a simple example taken from the Data QuickStart application public class RowMapperDao : AdoDaoSupport { private string cmdText = "select Address, City, CompanyName, ContactName, " + "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " + "Region from Customers"; public virtual IList<Customer> GetCustomers() { return AdoTemplate.QueryWithRowMapper<Customer>(CommandType.Text, cmdText, new CustomerRowMapper<Customer>()); } } where the implementation of the RowMapper is public class CustomerRowMapper<T> : IRowMapper<T> where T : Customer, new() { public T MapRow(IDataReader dataReader, int rowNum) { T customer = new T(); customer.Address = dataReader.GetString(0); customer.City = dataReader.GetString(1); customer.CompanyName = dataReader.GetString(2); customer.ContactName = dataReader.GetString(3); customer.ContactTitle = dataReader.GetString(4); customer.Country = dataReader.GetString(5); customer.Fax = dataReader.GetString(6); customer.Id = dataReader.GetString(7); customer.Phone = dataReader.GetString(8); customer.PostalCode = dataReader.GetString(9); customer.Region = dataReader.GetString(10); return customer; } } You may also pass in a delegate, which is particularly convenient if the mapping logic is short and you need to access local variables within the mapping logic. public virtual IList<Customer> GetCustomersWithDelegate() { return AdoTemplate.QueryWithRowMapperDelegate<Customer>(CommandType.Text, cmdText, delegate(IDataReader dataReader, int rowNum) { Customer customer = new Customer(); customer.Address = dataReader.GetString(0); customer.City = dataReader.GetString(1); customer.CompanyName = dataReader.GetString(2); customer.ContactName = dataReader.GetString(3); customer.ContactTitle = dataReader.GetString(4); customer.Country = dataReader.GetString(5); customer.Fax = dataReader.GetString(6); customer.Id = dataReader.GetString(7); customer.Phone = dataReader.GetString(8); customer.PostalCode = dataReader.GetString(9); customer.Region = dataReader.GetString(10); return customer; }); } The QueryForObject method is used when you expect there to be exactly one object returned from the mapping, otherwise a Spring.Dao.IncorrectResultSizeDataAccessException will be thrown. Here is some sample usage taken from the Data QuickStart. public class QueryForObjectDao : AdoDaoSupport { private string cmdText = "select Address, City, CompanyName, ContactName, " + "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " + "Region from Customers where ContactName = @ContactName"; public Customer GetCustomer(string contactName) { return AdoTemplate.QueryForObject(CommandType.Text, cmdText, new CustomerRowMapper<Customer>(), "ContactName", DbType.String, 30, contactName); } } There is a family of overloaded methods that allows you to
encapsulate and reuse a particular configuration of a
There is also the same methods with an additional collecting parameter to obtain any output parameters. These are
The IDbCommandCreator callback interface is shown below public interface IDbCommandCreator { IDbCommand CreateDbCommand(); } The created IDbCommand object is used when performing the QueryWithCommandCreator method. To process multiple result sets specify a list of named result set
processors,( i.e.
The list must contain objects of the type
public class NamedResultSetProcessor { public NamedResultSetProcessor(string name, IRowMapper rowMapper) { ... } public NamedResultSetProcessor(string name, IRowCallback rowcallback) { ... } public NamedResultSetProcessor(string name, IResultSetExtractor resultSetExtractor) { ... } . . . } The results of the RowMapper or ResultSetExtractor are retrieved by name from the dictionary that is returned. RowCallbacks, being stateless, only have the placeholder text, "ResultSet returned was processed by an IRowCallback" as a value for the name of the RowCallback used as a key. Output and InputOutput parameters can be retrieved by name. If this parameter name is null, then the index of the parameter prefixed with the letter 'P' is a key name, i.e P2, P3, etc. The namespace Spring.Data.Objects.Generic contains generic versions of these methods. These are listed below
and overloads that have an additional collecting parameter to obtain any output parameters.
When processing multiple result sets you can specify up to two type safe result set processors.
The list of result set processors contains either objects of the type Spring.Data.Generic.NamedResultSetProcessor<T> or Spring.Data.NamedResultSetProcessor. The generic result set processors, NamedResultSetProcessor<T>, is used to process the first result set in the case of using QueryWithCommandCreator<T> and to process the first and second result set in the case of using QueryWithCommandCreator<T,U>. Additional Spring.Data.NamedResultSetProcessors that are listed can be used to process additional result sets. If you specify a RowCallback with NamedResultSetProcessor<T>, you still need to specify a type parameter (say string) because the RowCallback processor does not return any object. It is up to subclasses of RowCallback to collect state due to processing the result set which is later queried. AdoTemplate contains several 'families' of methods to help remove boilerplate code and reduce common programming errors when using DataTables and DataSets. There are many methods in AdoTemplate so it is easy to feel a bit overwhelmed when taking a look at the SDK documentation. However, after a while you will hopefully find the class 'easy to navigate' with intellisense. Here is a quick categorization of the method names and their associated data access operation. Each method is overloaded to handle common cases of passing in parameter values. The 'catch-all' Execute methods upon which other functionality is built up upon are shown below. In Spring.Data.Core.AdoTemplate
Where public interface IDataAdapterCallback { object DoInDataAdapter(IDbDataAdapter dataAdapter); } The passed in There are type-safe versions of this method in
Where IDataAdapterCallback<T> and DataAdapterDelegate<T> are defined as public interface IDataAdapterCallback<T> { T DoInDataAdapter(IDbDataAdapter dataAdapter); } public delegate T DataAdapterDelegate<T>(IDbDataAdapter dataAdapter); DataTable operations are available on the class
DataSet operations are available on the class
The following code snippets demonstrate the basic functionality of these methods using the Northwind database. See the SDK documentation for more details on other overloaded methods. public class DataSetDemo : AdoDaoSupport { private string selectAll = @"select Address, City, CompanyName, ContactName, " + "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " + "Region from Customers"; public void DemoDataSetCreate() { DataSet customerDataSet = AdoTemplate.DataSetCreate(CommandType.Text, selectAll); // customerDataSet has a table named 'Table' with 91 rows customerDataSet = AdoTemplate.DataSetCreate(CommandType.Text, selectAll, new string[] { "Customers" }); // customerDataSet has a table named 'Customers' with 91 rows } public void DemoDataSetCreateWithParameters() { string selectLike = @"select Address, City, CompanyName, ContactName, " + "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " + "Region from Customers where ContactName like @ContactName"; DbParameters dbParameters = CreateDbParameters(); dbParameters.Add("ContactName", DbType.String).Value = "M%'; DataSet customerLikeMDataSet = AdoTemplate.DataSetCreateWithParams(CommandType.Text, selectLike, dbParameters); // customerLikeMDataSet has a table named 'Table' with 12 rows } public void DemoDataSetFill() { DataSet dataSet = new DataSet(); dataSet.Locale = CultureInfo.InvariantCulture; AdoTemplate.DataSetFill(dataSet, CommandType.Text, selectAll); } Updating a DataSet can be done using a CommandBuilder, automatically created from the specified select command and select parameters, or by explicitly specifying the insert, update, delete commands and parameters. Below is an example, refer to the SDK documentation for additional overloads public class DataSetDemo : AdoDaoSupport { private string selectAll = @"select Address, City, CompanyName, ContactName, " + "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " + "Region from Customers"; public void DemoDataSetUpdateWithCommandBuilder() { DataSet dataSet = new DataSet(); dataSet.Locale = CultureInfo.InvariantCulture; AdoTemplate.DataSetFill(dataSet, CommandType.Text, selectAll, new string[]{ "Customers" } ); AddAndEditRow(dataSet);. AdoTemplate.DataSetUpdateWithCommandBuilder(dataSet, CommandType.Text, selectAll, null, "Customers"); } public void DemoDataSetUpdateWithoutCommandBuilder() { DataSet dataSet = new DataSet(); dataSet.Locale = CultureInfo.InvariantCulture; AdoTemplate.DataSetFill(dataSet, CommandType.Text, selectAll, new string[]{ "Customers" } ); AddAndEditRow(dataSet);. string insertSql = @"INSERT Customers (CustomerID, CompanyName) VALUES (@CustomerId, @CompanyName)"; IDbParameters insertParams = CreateDbParameters(); insertParams.Add("CustomerId", DbType.String, 0, "CustomerId"); //.Value = "NewID"; insertParams.Add("CompanyName", DbType.String, 0, "CompanyName"); //.Value = "New Company Name"; string updateSql = @"update Customers SET Phone=@Phone where CustomerId = @CustomerId"; IDbParameters updateParams = CreateDbParameters(); updateParams.Add("Phone", DbType.String, 0, "Phone");//.Value = "030-0074322"; // simple change, last digit changed from 1 to 2. updateParams.Add("CustomerId", DbType.String, 0, "CustomerId");//.Value = "ALFKI"; AdoTemplate.DataSetUpdate(dataSet, "Customers", CommandType.Text, insertSql, insertParams, CommandType.Text, updateSql, updateParams, CommandType.Text, null , null); } private static void AddAndEditRow(DataSet dataSet) { DataRow dataRow = dataSet.Tables["Customers"].NewRow(); dataRow["CustomerId"] = "NewID"; dataRow["CompanyName"] = "New Company Name"; dataRow["ContactName"] = "New Name"; dataRow["ContactTitle"] = "New Contact Title"; dataRow["Address"] = "New Address"; dataRow["City"] = "New City"; dataRow["Region"] = "NR"; dataRow["PostalCode"] = "New Code"; dataRow["Country"] = "New Country"; dataRow["Phone"] = "New Phone"; dataRow["Fax"] = "New Fax"; dataSet.Tables["Customers"].Rows.Add(dataRow); DataRow alfkiDataRow = dataSet.Tables["Customers"].Rows[0]; alfkiDataRow["Phone"] = "030-0074322"; // simple change, last digit changed from 1 to 2. } } In the case of needing to set parameter SourceColumn or SourceVersion properties it may be more convenient to use IDbParameterBuilder. Typed DataSets need to have commands in their internal DataAdapters
and command collections explicitly set with a connection/transaction in
order for them to correctly participate with a surrounding transactional
context. The reason for this is by default the code generated is
explicitly managing the connections and transactions. This issue is very
well described in the article System.Transactions
and ADO.NET 2.0 by ADO.NET guru Sahil Malik. Spring offers a
convenience method that will use reflection to internally set the
transaction on the table adapter's internal command collection to the
ambient transaction. This method on the class
public PrintGroupMappingDataSet FindAll() { PrintGroupMappingTableAdapter adapter = new PrintGroupMappingTableAdapter(); PrintGroupMappingDataSet printGroupMappingDataSet = new PrintGroupMappingDataSet(); printGroupMappingDataSet = AdoTemplate.Execute(delegate(IDbCommand command) { TypedDataSetUtils.ApplyConnectionAndTx(adapter, command); adapter.Fill(printGroupMappingDataSet.PrintGroupMapping); return printGroupMappingDataSet; }) as PrintGroupMappingDataSet; return printGroupMappingDataSet; } This DAO method may be combined with other DAO operations inside a transactional context and they will all share the same connection/transaction objects. There are two overloads of the method ApplyConnectionAndTx which differ in the second method argument, one takes an IDbCommand and the other IDbProvider. These are listed below public static void ApplyConnectionAndTx(object typedDataSetAdapter, IDbCommand sourceCommand) public static void ApplyConnectionAndTx(object typedDataSetAdapter, IDbProvider dbProvider) The method that takes IDbCommand is a convenience if you will be using AdoTemplate callback's as the passed in command object will already have its connection and transaction properties set based on the current transactional context. The method that takes an IDbProvider is convenient to use when you have data access logic that is not contained within a single callback method but is instead spead among multiple classes. In this case passing the transactionally aware IDbCommand object can be intrusive on the method signatures. Instead you can pass in an instance of IDbProvider that can be obtained via standard dependency injection techniques or via a service locator style lookup. The
The
This class is concrete. Although it can be subclassed (for example to add a custom update method) it can easily be parameterized by setting SQL and declaring parameters. An example of an AdoQuery subclass to encapsulate an insert statement for a 'TestObject' (consisting only name and age columns) is shown below public class CreateTestObjectNonQuery : AdoNonQuery { private static string sql = "insert into TestObjects(Age,Name) values (@Age,@Name)"; public CreateTestObjectNonQuery(IDbProvider dbProvider) : base(dbProvider, sql) { DeclaredParameters.Add("Age", DbType.Int32); DeclaredParameters.Add("Name", SqlDbType.NVarChar, 16); Compile(); } public void Create(string name, int age) { ExecuteNonQuery(name, age); } }
public class TestObjectQuery : MappingAdoQuery { private static string sql = "select TestObjectNo, Age, Name from TestObjects"; public TestObjectQuery(IDbProvider dbProvider) : base(dbProvider, sql) { CommandType = CommandType.Text; } protected override object MapRow(IDataReader reader, int num) { TestObject to = new TestObject(); to.ObjectNumber = reader.GetInt32(0); to.Age = reader.GetInt32(1); to.Name = reader.GetString(2); return to; } } The
This class is concrete. Although it can be subclassed (for example to add a custom update method) it can easily be parameterized by setting SQL and declaring parameters. public class CreateTestObjectNonQuery : AdoNonQuery { private static string sql = "insert into TestObjects(Age,Name) values (@Age,@Name)"; public CreateTestObjectNonQuery(IDbProvider dbProvider) : base(dbProvider, sql) { DeclaredParameters.Add("Age", DbType.Int32); DeclaredParameters.Add("Name", SqlDbType.NVarChar, 16); Compile(); } public void Create(string name, int age) { ExecuteNonQuery(name, age); } } The StoredProcedure class is designed to make it as simple as possible to call a stored procedure. It takes advantage of metadata present in the database to look up names of in and out parameters.. This means that you don't have to explicitly declare parameters. You can of course still declare them if you prefer. There are two versions of the StoredProcedure class, one that uses generics and one that doesn't. Using the StoredProcedure class consists of two steps, first defining the in/out parameter and any object mappers and second executing the stored procedure. The non-generic version of StoredProcedure is in the namespace Spring.Data.Objects. It contains the following methods to execute a stored procedure
Each of these methods returns an The standard in/out parameters for the stored procedure can be set
programmatically by adding to the parameter collection exposed by the
property DeclaredParameters. For each result sets that is returned by
the stored procedures you can registering either an
Lets take a look at an example. The following stored procedure class will call the CustOrdersDetail stored procedure in the Northwind database, passing in the OrderID as a stored procedure argument and returning a collection of OrderDetails business objects. public class CustOrdersDetailStoredProc : StoredProcedure { private static string procedureName = "CustOrdersDetail"; public CustOrdersDetailStoredProc(IDbProvider dbProvider) : base(dbProvider, procedureName) { DeriveParameters(); AddRowMapper("orderDetailRowMapper", new OrderDetailRowMapper() ); Compile(); } public virtual IList GetOrderDetails(int orderid) { IDictionary outParams = Query(orderid); return outParams["orderDetailRowMapper"] as IList; } } The '
The The generic version of StoredProcedure is in the namespace Spring.Data.Objects.Generic. It allows you to define up to two generic type parameters that will be used to process result sets returned from the stored procedure. An example is shown below public class CustOrdersDetailStoredProc : StoredProcedure { private static string procedureName = "CustOrdersDetail"; public CustOrdersDetailStoredProc(IDbProvider dbProvider) : base(dbProvider, procedureName) { DeriveParameters(); AddRowMapper("orderDetailRowMapper", new OrderDetailRowMapper<OrderDetails>() ); Compile(); } public virtual List<OrderDetails> GetOrderDetails(int orderid) { IDictionary outParams = Query<OrderDetails>(orderid); return outParams["orderDetailRowMapper"] as List<OrderDetails>; } } You can find ready to run code demonstrating the StoredProcedure class in the example 'Data Access' that is part of the Spring.NET distribution.
|