两个表的类如上一篇<<2个表关联查询>>
这里讨论的是使用我们习惯的inner join的Sql语句来关联我们的数据表
唯一有区别的在这里
Book.xml
<resultMap id="get-book-note" class="com.it.Book" groupBy="Book.oid">
<result property="oid" column="oid"/>
<result property="name" column="name"/>
<result property="notes" resultMap="get-note" />
</resultMap>
<resultMap id="get-note" class="Note">
<result property="sid" column="sid" />
<result property="sname" column="sname" />
</resultMap>
<select id="getProduct" resultMap="get-book-note">
<![CDATA[
SELECT
book.oid,
book.name,
note.sid,
note.sname
FROM
book,note where note.book_oid = book.oid
]]>
</select>
<result property="oid" column="oid"/>
<result property="name" column="name"/>
<result property="notes" resultMap="get-note" />
</resultMap>
<resultMap id="get-note" class="Note">
<result property="sid" column="sid" />
<result property="sname" column="sname" />
</resultMap>
<select id="getProduct" resultMap="get-book-note">
<![CDATA[
SELECT
book.oid,
book.name,
note.sid,
note.sname
FROM
book,note where note.book_oid = book.oid
]]>
</select>
注意点 : 1. Sql语句中出现的所有字段,都必须在resultMap中有体现,否则查询出来的字段默认为null;
2. 父表关联子表,需要加
<result property="notes" resultMap="get-note" />
其中property必须在类里有相关的notes属性及其方法来获取子类,后取得结果必须是子类的resultMap 的Id
3. select 语句中的resultMap对应于父类的resultMap的名称
测试语句’Main.java
//测试2个表关联 author :meetweb
try {
Book Book1 =new Book();
Book1.setOid(1);
List<Book> books=sqlMapClinet.queryForList("getProduct");
System.out.println(books.size());
for (Iterator iterator = books.iterator(); iterator.hasNext();) {
Book Bookk = (Book) iterator.next();
System.out.println(Bookk.getName());
List<Note> l=Bookk.getNotes();
System.out.println(((Note)l.get(0)).getSname());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Book Book1 =new Book();
Book1.setOid(1);
List<Book> books=sqlMapClinet.queryForList("getProduct");
System.out.println(books.size());
for (Iterator iterator = books.iterator(); iterator.hasNext();) {
Book Bookk = (Book) iterator.next();
System.out.println(Bookk.getName());
List<Note> l=Bookk.getNotes();
System.out.println(((Note)l.get(0)).getSname());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
原创作品,转载请注明作者