Mybatis 文档篇 3.1:Mapper XML 之 sel

2019-03-22  本文已影响0人  兆雪儿

1 Mapper XML

2 select

The select statement is one of the most popular elements that you'll use in MyBatis. Putting data in a database isn't terribly valuable until you get it back out, so most applications query far more than they modify the data.
在 MyBatis 中,查询语句是最常用的语句之一。向数据库中放入数据并没有多大价值,直到你再将它取出,因此大多数的应用中查询比修改数据多的多。

For every insert, update or delete, there are probably many selects. This is one of the founding principles of MyBatis, and is the reason so much focus and effort was placed on querying and result mapping.
对每个插入、修改或删除操作,通常都对应很多的查询操作。这是 MyBatis 的一个基本原则,也是 MyBatis 在查询和结果映射方面如此关注和努力的原因。

2.1 select 元素

The select element is quite simple for simple cases.
对于简单情况而言,select 元素是相当简单的。

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

This statement is called selectPerson, takes a parameter of type int (or Integer), and returns a HashMap keyed by column names mapped to row values.
这个语句被命名为 selectPerson,接收一个 int(或 Integer)类型的参数,并且返回一个 HashMap 类型的对象,其中,键是列名,值为结果行中对应的值。

Notice the parameter notation: #{id} 。This tells MyBatis to create a PreparedStatement parameter. With JDBC, such a parameter would be identified by a "?" in SQL passed to a new PreparedStatement, something like this:
注意参数标记:#{id}。它告诉 MyBatis 创建一个 PreparedStatement 参数。使用 JDBC 时,这样的一个参数在 SQL 中会由一个“?”标识,并传递给一个新的 PreparedStatement。 就像这样:

// 简单的 JDBC 代码, 不是 MyBatis…
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);

Of course, there's a lot more code required by JDBC alone to extract the results and map them to an instance of an object, which is what MyBatis saves you from having to do.
当然,这需要很多单独的 JDBC 代码来提取结果并将它们映射到一个对象实例中,这就是 MyBatis 为你节省精力和时间的地方。

2.2 select 的属性

The select element has more attributes that allow you to configure the details of how each statement should behave.
select 元素提供很多属性来允许你配置每个语句该如何表现的细节。

<select
  id="selectPerson"
  parameterType="int"
  parameterMap="deprecated"
  resultType="hashmap"
  resultMap="personResultMap"
  flushCache="false"
  useCache="true"
  timeout="10000"
  fetchSize="256"
  statementType="PREPARED"
  resultSetType="FORWARD_ONLY">

最后

说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

当前版本:mybatis-3.5.0
官网文档:MyBatis
官网翻译:MyBatis 简体中文
项目实践:MyBatis Learn

上一篇 下一篇

猜你喜欢

热点阅读