使用了Mybatis的懒加载,即
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 按需延迟加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
xml中
<select id="queryByID" resultMap="pojoResultMap">
SELECT
*
FROM
<include refid="tableName"/>
WHERE order_id = #{id};
</select>
<sql id="tableName">tb_order</sql>
<resultMap type="Order" id="pojoResultMap" autoMapping="true">
<id column="order_id" property="orderId"/>
<association property="orderShipping" javaType="OrderShipping" column="order_id" select="queryOrderShippingByOrderId" autoMapping="true"></association>
<collection property="orderItems" javaType="Arraylist" ofType="OrderItem" autoMapping="true" select="queryOrderItemByOrderId" column="order_id">
</collection>
</resultMap>
<select id="queryOrderShippingByOrderId" resultType="OrderShipping" parameterType="String">
SELECT * FROM tb_order_shipping WHERE order_id = #{orderId};
</select>
<select id="queryOrderItemByOrderId" resultType="OrderItem" parameterType="String">
SELECT * FROM tb_order_item WHERE order_id = #{orderId};
</select>
Order类,只列出部分属性:
public class Order {
private String orderId;//id+时间戳
@NotEmpty
private List<OrderItem> orderItems;//商品详情
private OrderShipping orderShipping; //物流地址信息
setter和getter略
}
查询Order时会出现两个问题,出现问题的本质原因是:这种查询返回的Order对象会多一个handler属性(代理对象):
1、如果使用springmvc返回json会报解析错误。解决方法是写一个Mapper继承ObjectMapper
public class CustomMapper extends ObjectMapper {
/**
*
*/
private static final long serialVersionUID = 1L;
public CustomMapper() {
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
然后在spring-servlet.xml的<mvc:annotation-driven>下面<mvc:message-converters>追加:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!-- 配置 objectMapper 为我们自定义扩展后的 CustomMapper -->
<property name="objectMapper">
<bean class="com.taotao.store.order.util.CustomMapper">
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
这个作用其实就是在解析时忽略对象中某些不存在的属性。比如Order类中根本没有handler属性。
2、当我们以调api方式获取resposeBody的json字符串后,要做反序列化,比如Order order = MAPPER.readValue(respBody, Order.class);
但Order中没有handler属性,respBody中有handler属性,那怎么办?
第一种方法:要对MAPPER进行配置,即在使用前调用MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);这样就不会解析这种不存在的属性了
第二种方法:在pojo类上使用@JsonIgnoreProperties(ignoreUnknown = true),比如在Order类上用这个注解。注意,这个注解无法解决上面第一个问题。
---------------------------------------
List<Cart> list = MAPPER.readValue(respBody,
MAPPER.getTypeFactory().constructCollectionType(List.class, Cart.class));