mybatis获取对象及其关联对象的两种方式

场景如下:有一个Book类,一个Category类,Book类有一个对Category的引用,要求获取Book对象的同时取出Category对象

Book.java类代码如下

public class Book implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8634505584095346474L;

	private String id;
	private String name;
	private Date publishDate;
	private String author;
	private Float price;
	private Category category;
	private Long quantity;
        // setter and getter method is omited!
}

 Category.java类代码如下

 

public class Category implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8964146416205979692L;

	private String id;
	private String name;
	private String spell;
	private String comments;
        //setter and getter method is omited!
}

 对应获取Book对象的两种方式,通过配置BookMapper.xml中实现

 

方式一(通过配置映射实现):

<resultMap id="bookMap" type="Book">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="publishDate" column="publishDate"/>
<result property="author" column="author"/>
<result property="price" column="price"/>
<result property="quantity" column="quantity"/>
<association property="category" javaType="Category">
   <id property="id" column="category_id" javaType="string"/>
   <id property="name" column="category_name"/>
   <id property="spell" column="category_spell"/>
   <id property="comments" column="category_comments"/>
</association>
</resultMap>

<select id="getBook" parameterType="string" resultMap="bookMap">
select b.id,
         b.name,
         b.publishDate,
         b.author,
         b.price,
         b.category,
         b.quantity,
         c.id as category_id,
         c.name as category_name,
         c.spell as category_spell,
         c.comments as category_comments 
from t_book b left outer join t_bookcategory c on b.category=c.id where b.id=#{id}
</select>

 方式二(通过OGNL实现):

 

<select id="getBook" parameterType="string" resultType="Book">
select b.id,
      b.name,
      b.publishDate,
      b.author,
      b.price,
      b.quantity,
      c.id as "category.id",
      c.name as "category.name",
      c.spell as "category.spell",
      c.comments as "category.comments" 
from t_book b left outer join t_bookcategory c on b.category=c.id where b.id=#{id}
</select>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值