场景如下:有一个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>