将JDBC操作建模为Java对象

org.springframework.jdbc.object包含的类允许您以更面向对象的方式访问数据库。例如,您可以运行查询并将结果作为包含将关系列数据映射到业务对象属性的列表返回。您还可以运行存储过程以及运行更新、删除和插入语句。

许多Spring开发人员认为下面描述的各种RDBMS操作类(除了StoredProcedure类)通常可以用直接的JdbcTemplate调用来替代。通常,编写一个调用JdbcTemplate上的方法的DAO方法更简单(而不是将查询封装为一个完整的类)。

但是,如果您正在使用RDBMS操作类获得可衡量的价值,那么应继续使用这些类。

理解SqlQuery

SqlQuery是一个可重用、线程安全的类,封装了一个SQL查询。子类必须实现newRowMapper(..)方法,以提供一个RowMapper实例,该实例可以在执行查询期间从遍历ResultSet获取的每一行中创建一个对象。很少直接使用SqlQuery类,因为MappingSqlQuery子类提供了一个更方便的实现,用于将行映射到Java类。扩展SqlQuery的其他实现包括MappingSqlQueryWithParametersUpdatableSqlQuery

使用MappingSqlQuery

MappingSqlQuery是一个可重用的查询,在其中具体子类必须实现抽象的mapRow(..)方法,将提供的ResultSet的每一行转换为指定类型的对象。以下示例显示了一个自定义查询,将t_actor关系中的数据映射到Actor类的实例:

  • Java

  • Kotlin

public class ActorMappingQuery extends MappingSqlQuery<Actor> {

	public ActorMappingQuery(DataSource ds) {
		super(ds, "select id, first_name, last_name from t_actor where id = ?");
		declareParameter(new SqlParameter("id", Types.INTEGER));
		compile();
	}

	@Override
	protected Actor mapRow(ResultSet rs, int rowNumber) throws SQLException {
		Actor actor = new Actor();
		actor.setId(rs.getLong("id"));
		actor.setFirstName(rs.getString("first_name"));
		actor.setLastName(rs.getString("last_name"));
		return actor;
	}
}
class ActorMappingQuery(ds: DataSource) : MappingSqlQuery<Actor>(ds, "select id, first_name, last_name from t_actor where id = ?") {

	init {
		declareParameter(SqlParameter("id", Types.INTEGER))
		compile()
	}

	override fun mapRow(rs: ResultSet, rowNumber: Int) = Actor(
			rs.getLong("id"),
			rs.getString("first_name"),
			rs.getString("last_name")
	)
}

该类扩展了参数化为Actor类型的MappingSqlQuery。此自定义查询的构造函数接受一个DataSource作为唯一参数。在此构造函数中,您可以调用超类的构造函数,传入DataSource和应该运行以检索此查询的行的SQL。此SQL用于创建一个PreparedStatement,因此它可能包含在执行期间传入的任何参数的占位符。您必须使用declareParameter方法声明每个参数,传入一个SqlParameterSqlParameter接受一个名称和在java.sql.Types中定义的JDBC类型。定义所有参数后,可以调用compile()方法,以便准备并稍后运行该语句。此类在编译后是线程安全的,因此只要在DAO初始化时创建这些实例,它们可以保留为实例变量并被重用。以下示例显示了如何定义这样的类:

  • Java

  • Kotlin

private ActorMappingQuery actorMappingQuery;

@Autowired
public void setDataSource(DataSource dataSource) {
	this.actorMappingQuery = new ActorMappingQuery(dataSource);
}

public Customer getCustomer(Long id) {
	return actorMappingQuery.findObject(id);
}
private val actorMappingQuery = ActorMappingQuery(dataSource)

fun getCustomer(id: Long) = actorMappingQuery.findObject(id)

上面示例中的方法检索传入的id的客户。由于我们只希望返回一个对象,因此我们使用findObject便利方法,并将id作为参数。如果我们有一个返回对象列表并接受其他参数的查询,我们将使用接受作为可变参数传入的参数值数组的execute方法之一。以下示例显示了这样一个方法:

  • Java

  • Kotlin

public List<Actor> searchForActors(int age, String namePattern) {
	return actorSearchMappingQuery.execute(age, namePattern);
}
fun searchForActors(age: Int, namePattern: String) =
			actorSearchMappingQuery.execute(age, namePattern)

使用 SqlUpdate

SqlUpdate 类封装了一个 SQL 更新操作。与查询一样,更新对象是可重用的,并且与所有 RdbmsOperation 类一样,更新可以具有参数并且在 SQL 中定义。该类提供了许多类似于查询对象的 execute(..) 方法的 update(..) 方法。 SqlUpdate 类是具体的。它可以被子类化,例如,添加自定义更新方法。但是,您不必对 SqlUpdate 类进行子类化,因为可以通过设置 SQL 和声明参数来轻松地对其进行参数化。以下示例创建了一个名为 execute 的自定义更新方法:

  • Java

  • Kotlin

import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;

public class UpdateCreditRating extends SqlUpdate {

	public UpdateCreditRating(DataSource ds) {
		setDataSource(ds);
		setSql("update customer set credit_rating = ? where id = ?");
		declareParameter(new SqlParameter("creditRating", Types.NUMERIC));
		declareParameter(new SqlParameter("id", Types.NUMERIC));
		compile();
	}

	/**
	 * @param id for the Customer to be updated
	 * @param rating the new value for credit rating
	 * @return number of rows updated
	 */
	public int execute(int id, int rating) {
		return update(rating, id);
	}
}
import java.sql.Types
import javax.sql.DataSource
import org.springframework.jdbc.core.SqlParameter
import org.springframework.jdbc.object.SqlUpdate

class UpdateCreditRating(ds: DataSource) : SqlUpdate() {

	init {
		setDataSource(ds)
		sql = "update customer set credit_rating = ? where id = ?"
		declareParameter(SqlParameter("creditRating", Types.NUMERIC))
		declareParameter(SqlParameter("id", Types.NUMERIC))
		compile()
	}

	/**
	 * @param id for the Customer to be updated
	 * @param rating the new value for credit rating
	 * @return number of rows updated
	 */
	fun execute(id: Int, rating: Int): Int {
		return update(rating, id)
	}
}

使用 StoredProcedure

StoredProcedure类是RDBMS存储过程对象抽象的abstract超类。

继承的sql属性是RDBMS中存储过程的名称。

要为StoredProcedure类定义参数,可以使用SqlParameter或其子类之一。您必须在构造函数中指定参数名称和SQL类型,如下面的代码片段所示:

  • Java

  • Kotlin

new SqlParameter("in_id", Types.NUMERIC),
new SqlOutParameter("out_first_name", Types.VARCHAR),
SqlParameter("in_id", Types.NUMERIC),
SqlOutParameter("out_first_name", Types.VARCHAR),

使用java.sql.Types常量指定SQL类型。

第一行(带有SqlParameter)声明了一个IN参数。您可以在存储过程调用和使用SqlQuery及其子类的查询中都使用IN参数(在了解SqlQuery中有介绍)。

第二行(带有SqlOutParameter)声明了一个out参数,用于存储过程调用。还有一个SqlInOutParameter用于InOut参数(为存储过程提供一个in值并返回一个值的参数)。

对于in参数,除了名称和SQL类型外,您还可以为数字数据指定一个比例或为自定义数据库类型指定一个类型名称。对于out参数,您可以提供一个RowMapper来处理从REF游标返回的行的映射。另一个选项是指定一个SqlReturnType,允许您定义返回值的自定义处理。

下一个简单DAO的示例使用StoredProcedure调用一个函数(sysdate()),该函数在任何Oracle数据库中都有。要使用存储过程功能,您必须创建一个扩展StoredProcedure的类。在此示例中,StoredProcedure类是一个内部类。但是,如果您需要重用StoredProcedure,可以将其声明为顶级类。此示例没有输入参数,但是使用SqlOutParameter类将输出参数声明为日期类型。execute()方法运行该过程并从结果Map中提取返回的日期。结果Map对于每个声明的输出参数(在本例中仅有一个)都有一个条目,使用参数名称作为键。以下清单显示了我们的自定义StoredProcedure类:

  • Java

  • Kotlin

import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class StoredProcedureDao {

	private GetSysdateProcedure getSysdate;

	@Autowired
	public void init(DataSource dataSource) {
		this.getSysdate = new GetSysdateProcedure(dataSource);
	}

	public Date getSysdate() {
		return getSysdate.execute();
	}

	private class GetSysdateProcedure extends StoredProcedure {

		private static final String SQL = "sysdate";

		public GetSysdateProcedure(DataSource dataSource) {
			setDataSource(dataSource);
			setFunction(true);
			setSql(SQL);
			declareParameter(new SqlOutParameter("date", Types.DATE));
			compile();
		}

		public Date execute() {
			// the 'sysdate' sproc has no input parameters, so an empty Map is supplied...
			Map<String, Object> results = execute(new HashMap<String, Object>());
			Date sysdate = (Date) results.get("date");
			return sysdate;
		}
	}

}
import java.sql.Types
import java.util.Date
import java.util.Map
import javax.sql.DataSource
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.object.StoredProcedure

class StoredProcedureDao(dataSource: DataSource) {

	private val SQL = "sysdate"

	private val getSysdate = GetSysdateProcedure(dataSource)

	val sysdate: Date
		get() = getSysdate.execute()

	private inner class GetSysdateProcedure(dataSource: DataSource) : StoredProcedure() {

		init {
			setDataSource(dataSource)
			isFunction = true
			sql = SQL
			declareParameter(SqlOutParameter("date", Types.DATE))
			compile()
		}

		fun execute(): Date {
			// the 'sysdate' sproc has no input parameters, so an empty Map is supplied...
			val results = execute(mutableMapOf<String, Any>())
			return results["date"] as Date
		}
	}
}

下面的StoredProcedure示例有两个输出参数(在本例中为Oracle REF游标):

  • Java

  • Kotlin

import java.util.HashMap;
import java.util Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class TitlesAndGenresStoredProcedure extends StoredProcedure {

	private static final String SPROC_NAME = "AllTitlesAndGenres";

	public TitlesAndGenresStoredProcedure(DataSource dataSource) {
		super(dataSource, SPROC_NAME);
		declareParameter(new SqlOutParameter("titles", OracleTypes.CURSOR, new TitleMapper()));
		declareParameter(new SqlOutParameter("genres", OracleTypes.CURSOR, new GenreMapper()));
		compile();
	}

	public Map<String, Object> execute() {
		// again, this sproc has no input parameters, so an empty Map is supplied
		return super.execute(new HashMap<String, Object>());
	}
}
import java.util.HashMap
import javax.sql.DataSource
import oracle.jdbc.OracleTypes
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.object.StoredProcedure

class TitlesAndGenresStoredProcedure(dataSource: DataSource) : StoredProcedure(dataSource, SPROC_NAME) {

	companion object {
		private const val SPROC_NAME = "AllTitlesAndGenres"
	}

	init {
		declareParameter(SqlOutParameter("titles", OracleTypes.CURSOR, TitleMapper()))
		declareParameter(SqlOutParameter("genres", OracleTypes.CURSOR, GenreMapper()))
		compile()
	}

	fun execute(): Map<String, Any> {
		// again, this sproc has no input parameters, so an empty Map is supplied
		return super.execute(HashMap<String, Any>())
	}
}

请注意,在TitlesAndGenresStoredProcedure构造函数中使用的declareParameter(..)方法的重载变体传递了RowMapper实现实例。这是一种非常方便和强大的重用现有功能的方式。接下来的两个示例提供了两个RowMapper实现的代码。

TitleMapper类将ResultSet映射到每行中提供的ResultSetTitle域对象,如下所示:

  • Java

  • Kotlin

import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Title;
import org.springframework.jdbc.core RowMapper;

public final class TitleMapper implements RowMapper<Title> {

	public Title mapRow(ResultSet rs, int rowNum) throws SQLException {
		Title title = new Title();
		title.setId(rs.getLong("id"));
		title.setName(rs.getString("name"));
		return title;
	}
}
import java.sql.ResultSet
import com.foo.domain.Title
import org.springframework.jdbc.core RowMapper

class TitleMapper : RowMapper<Title> {

	override fun mapRow(rs: ResultSet, rowNum: Int) =
			Title(rs.getLong("id"), rs.getString("name"))
}

The GenreMapper class maps a ResultSet to a Genre domain object for each row in the supplied ResultSet, as follows:

  • Java

  • Kotlin

import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Genre;
import org.springframework.jdbc.core.RowMapper;

public final class GenreMapper implements RowMapper<Genre> {

	public Genre mapRow(ResultSet rs, int rowNum) throws SQLException {
		return new Genre(rs.getString("name"));
	}
}
import java.sql.ResultSet
import com.foo.domain.Genre
import org.springframework.jdbc.core.RowMapper

class GenreMapper : RowMapper<Genre> {

	override fun mapRow(rs: ResultSet, rowNum: Int): Genre {
		return Genre(rs.getString("name"))
	}
}

To pass parameters to a stored procedure that has one or more input parameters in its definition in the RDBMS, you can code a strongly typed execute(..) method that would delegate to the untyped execute(Map) method in the superclass, as the following example shows:

  • Java

  • Kotlin

import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class TitlesAfterDateStoredProcedure extends StoredProcedure {

	private static final String SPROC_NAME = "TitlesAfterDate";
	private static final String CUTOFF_DATE_PARAM = "cutoffDate";

	public TitlesAfterDateStoredProcedure(DataSource dataSource) {
		super(dataSource, SPROC_NAME);
		declareParameter(new SqlParameter(CUTOFF_DATE_PARAM, Types.DATE);
		declareParameter(new SqlOutParameter("titles", OracleTypes.CURSOR, new TitleMapper()));
		compile();
	}

	public Map<String, Object> execute(Date cutoffDate) {
		Map<String, Object> inputs = new HashMap<String, Object>();
		inputs.put(CUTOFF_DATE_PARAM, cutoffDate);
		return super.execute(inputs);
	}
}
import java.sql.Types
import java.util.Date
import javax.sql.DataSource
import oracle.jdbc.OracleTypes
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.core.SqlParameter
import org.springframework.jdbc.object.StoredProcedure

class TitlesAfterDateStoredProcedure(dataSource: DataSource) : StoredProcedure(dataSource, SPROC_NAME) {

	companion object {
		private const val SPROC_NAME = "TitlesAfterDate"
		private const val CUTOFF_DATE_PARAM = "cutoffDate"
	}

	init {
		declareParameter(SqlParameter(CUTOFF_DATE_PARAM, Types.DATE))
		declareParameter(SqlOutParameter("titles", OracleTypes.CURSOR, TitleMapper()))
		compile()
	}

	fun execute(cutoffDate: Date) = super.execute(
			mapOf<String, Any>(CUTOFF_DATE_PARAM to cutoffDate))
}