Skip to content

Instantly share code, notes, and snippets.

@bfchengnuo
Created June 6, 2018 03:43
Show Gist options
  • Save bfchengnuo/69f27b9745e1f4e4b7fe0ed7e914ba9c to your computer and use it in GitHub Desktop.
Save bfchengnuo/69f27b9745e1f4e4b7fe0ed7e914ba9c to your computer and use it in GitHub Desktop.
一对一关系映射

说的是一对一的关联查询,在映射的时候的几种写法:

常规写法:

<select id="findAliasByPid" parameterType="long" resultType="org.sang.bean.Alias">
  SELECT * FROM alias WHERE pid=#{id}
</select>

<resultMap id="provinceResultMapper" type="org.sang.bean.Province">
  <id column="id" property="id"/>
  <association property="alias" column="id" select="org.sang.db.AliasMapper.findAliasByPid"/>
</resultMap>

使用 association 来处理一对一的关系,select 和 column 分别指代:执行的 sql 语句和传入参数。 他们是可以省略的,比如直接写在 select 中,然后使用这种写法:

<association property="author" javaType="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
  <result property="password" column="author_password"/>
  <result property="email" column="author_email"/>
  <result property="bio" column="author_bio"/>
  <result property="favouriteSection" column="author_favourite_section"/>
</association>

后来偶然一次,我发现对于简单的映射,可以直接“点”着写,就像这样:

<resultMap id="stu_map" type="stu">
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  <result property="age" column="age"/>
  <result property="birth" column="birth"/>
  <result property="email" column="email"/>
  <result property="school.id" column="sid"/>
  <result property="school.name" column="sname"/>
  <result property="school.loc" column="loc"/>
</resultMap>

对于名称一致的属性,其实可以直接开启自动映射的,autoMapping 属性,省点劲......

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment