mybatis3.2.7学习笔记2_一对一、一对多、多对多、延时加载、缓存

4 篇文章 0 订阅

 

参考源:

http://java.itcast.cn/news/20150512/13543033211.shtml 这是传智播客的燕青老师讲的 讲的很好 强烈推荐

 hibernate 一对一 一对多 多对多 http://blog.csdn.net/undergrowth/article/details/12281771

  我对比了一下mybatis和hibernate的一对一 一对多 多对多的概念

  mybatis的要比hibernate简单的多  更加突出了mybatis注重sql的概念


* resuType--将sql的列名和pojo的属性进行一一的映射
 *  resultMap--可以避免使用resultType方式的重复记录
 * association--将sql列映射到pojo对象中 collection--将关联信息映射到list列表中
 * association、collection都具备延时加载功能 mybatis具有二级缓存
 * SqlSession--一级缓存,当SqlSession未关闭时,使用key-value的形式存储对象,当进行增加、删除、修改时,都会清空一级缓存中的数据
 * Mapper命名空间--二级缓存,二级缓存的接口为Cache
 * ,mybatis提供的二级缓存默认实现为PerpetualCache,以Mapper的命名空间为单位进行缓存
 * ,可跨多个SqlSession,当SqlSession关闭时
 * ,将一级缓存的对象写入到二级缓存,要进行二级缓存的对象必须序列化,因为二级缓存不一定在内存中,可能在硬盘
 *  当进行增加、删除、修改时,都会清空二级缓存中的数据
*  useCache="true"  
 *  flushCache="true"




Mapper的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 使用Mapper代理开发 namespace的值与mapper的接口包 -->
<mapper namespace="com.undergrowth.mybatis.mapper.OrderUserMapper">
	<!-- 使用resultType进行一对一的映射 -->
	<select id="findOrdersUserByResultType" resultType="com.undergrowth.mybatis.po.OrdersUser">
		select
		orders.*,user.username,user.birthday from orders,user where
		orders.user_id=user.id
	</select>
	<!-- 使用resultMap进行一对一的映射 -->
	<resultMap type="com.undergrowth.mybatis.po.OrdersUserPojo"
		id="findOrdersUserByResultMapId">
		<result column="id" property="id" />
		<result column="user_id" property="user_id" />
		<result column="number" property="number" />
		<result column="createtime" property="createtime" />
		<result column="note" property="note" />

		<association property="user" javaType="com.undergrowth.mybatis.po.User">
			<result column="username" property="username" />
			<result column="birthday" property="birthday" />
		</association>
	</resultMap>

	<!-- 使用resultMap进行一对一的映射 -->
	<select id="findOrdersUserByResultMap" resultMap="findOrdersUserByResultMapId">
		select
		orders.*,user.username,user.birthday from orders,user where
		orders.user_id=user.id
	</select>

	<!-- 使用collection进行集合元素的映射 映射成一对多 避免记录的重复 -->
	<!-- 使用extends使orders与user不用进行映射 -->
	<resultMap type="com.undergrowth.mybatis.po.OrdersUserDetailPojo"
		id="findOrderUserDetailResultMapId" extends="findOrdersUserByResultMapId">
		<collection property="orderDetails"
			ofType="com.undergrowth.mybatis.po.OrderDetail">
			<result column="orders_id" property="orders_id" />
			<result column="items_id" property="items_id" />
			<result column="items_num" property="items_num" />
		</collection>
	</resultMap>

	<select id="findOrderUserDetailResultMap" resultMap="findOrderUserDetailResultMapId">
		SELECT
		orders.*,
		user.username,
		user.birthday,
		orderdetail.orders_id,
		orderdetail.items_id,
		orderdetail.items_num
		FROM
		orders,
		user,
		orderdetail
		WHERE
		orders.user_id = user.id
		AND orders.id = orderdetail.orders_id
	</select>

	<resultMap type="com.undergrowth.mybatis.po.UserToOrdersVo"
		id="findUserAndItemsResultMapId">
		<result column="user_id" property="id" />
		<result column="username" property="username" />
		<result column="birthday" property="birthday" />
		<result column="sex" property="sex" />
		<result column="user_address" property="address" />

		<!-- 关联订单列表 -->
		<collection property="orderList"
			ofType="com.undergrowth.mybatis.po.OrdersToOrderDetailVo">
			<result column="id" property="id" />
			<result column="user_id" property="user_id" />
			<result column="number" property="number" />
			<result column="createtime" property="createtime" />
			<result column="note" property="note" />
			<!-- 订单关联明细 -->
			<collection property="orderDetailList"
				ofType="com.undergrowth.mybatis.po.OrderDetailToItems">
				<result column="orders_id" property="orders_id" />
				<result column="items_id" property="items_id" />
				<result column="items_num" property="items_num" />
				<!-- 关联商品 -->
				<association property="items" javaType="com.undergrowth.mybatis.po.Items">
					<result column="name" property="name" />
					<result column="price" property="price" />
					<result column="detail" property="detail" />
				</association>
			</collection>
		</collection>
	</resultMap>

	<!-- 使用 collection和association进行用户和商品明细的多对多的映射 -->
	<select id="findUserAndItemsResultMap" resultMap="findUserAndItemsResultMapId">

		SELECT
		orders.*,
		user.username,
		user.birthday,
		user.sex,
		user.address
		user_address,
		orderdetail.orders_id,
		orderdetail.items_id,
		orderdetail.items_num,
		items.name,
		items.price,
		items.detail
		FROM
		orders,
		user,
		orderdetail,
		items
		WHERE
		orders.user_id =
		user.id
		AND orders.id =
		orderdetail.orders_id
		AND orderdetail.items_id =
		items.id
	</select>

	<select id="findUserById" resultType="com.undergrowth.mybatis.po.User">
		select * from user where id=#{value}
	</select>

	<!-- 延时加载 association -->
	<resultMap type="com.undergrowth.mybatis.po.OrdersUserPojo"
		id="findOrderUserLazyLoadingId">
		<result column="id" property="id" />
		<result column="user_id" property="user_id" />
		<result column="number" property="number" />
		<result column="createtime" property="createtime" />
		<result column="note" property="note" />
		<association property="user" javaType="com.undergrowth.mybatis.po.User"
			select="findUserById" column="user_id"></association>
	</resultMap>
	<select id="findOrderUserLazyLoading" resultMap="findOrderUserLazyLoadingId">
		select * from
		orders
	</select>
   <!-- 开启Mapper的二级缓存 默认实现为PerpetualCache -->
   <cache></cache>
</mapper>



接口文件

package com.undergrowth.mybatis.mapper;

import java.util.List;

import com.undergrowth.mybatis.po.OrdersUser;
import com.undergrowth.mybatis.po.OrdersUserDetailPojo;
import com.undergrowth.mybatis.po.OrdersUserPojo;
import com.undergrowth.mybatis.po.UserToOrdersVo;

/**
 * 通过
 * @author u1
 *
 */
public interface OrderUserMapper {

	public List<OrdersUser> findOrdersUserByResultType();
	public List<OrdersUserPojo> findOrdersUserByResultMap();
	public List<OrdersUserDetailPojo> findOrderUserDetailResultMap();
	public List<UserToOrdersVo> findUserAndItemsResultMap();
	public List<OrdersUserPojo> findOrderUserLazyLoading();
}



测试代码

package com.undergrowth.mybatis.dao;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;

import com.undergrowth.mybatis.mapper.OrderUserMapper;
import com.undergrowth.mybatis.po.OrdersUser;
import com.undergrowth.mybatis.po.OrdersUserDetailPojo;
import com.undergrowth.mybatis.po.OrdersUserPojo;
import com.undergrowth.mybatis.po.UserToOrdersVo;
import com.undergrowth.mybatis.util.SqlSessionUtil;

/**
 * 测试代码 
 * resuType--将sql的列名和pojo的属性进行一一的映射 
 * resultMap--可以避免使用resultType方式的重复记录
 * association--将sql列映射到pojo对象中 collection--将关联信息映射到list列表中
 * association、collection都具备延时加载功能
 *  mybatis具有二级缓存
 * SqlSession--一级缓存,当SqlSession未关闭时,使用key-value的形式存储对象
 * Mapper命名空间--二级缓存,二级缓存的接口为Cache
 * ,mybatis提供的二级缓存默认实现为PerpetualCache,以Mapper的命名空间为单位进行缓存,可跨多个SqlSession
 * 要进行二级缓存的对象必须序列化
 * @author u1
 * 
 */
public class OrderUserMapperDao {

	SqlSessionFactory sqlSessionFactory = null;

	@Before
	public void before() throws IOException {
		sqlSessionFactory = SqlSessionUtil
				.getSqlSessionFactory("mybatis-conf.xml");
	}

	/**
	 * 使用resultType进行一对一的映射
	 */
	@Test
	public void testOneToOne() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			OrderUserMapper orderUserMapper = sqlSession
					.getMapper(OrderUserMapper.class);
			List<OrdersUser> ordersUsers = orderUserMapper
					.findOrdersUserByResultType();
			for (OrdersUser ordersUser : ordersUsers) {
				System.out.println(ordersUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * 使用resultMap进行一对一的映射
	 */
	@Test
	public void testOneToOneResultMap() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			OrderUserMapper orderUserMapper = sqlSession
					.getMapper(OrderUserMapper.class);
			List<OrdersUserPojo> ordersUsers = orderUserMapper
					.findOrdersUserByResultMap();
			for (OrdersUserPojo ordersUser : ordersUsers) {
				System.out.println(ordersUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * 使用resultMap和collection进行一对多的映射
	 */
	@Test
	public void findOrderUserDetailResultMap() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			OrderUserMapper orderUserMapper = sqlSession
					.getMapper(OrderUserMapper.class);
			List<OrdersUserDetailPojo> ordersUsers = orderUserMapper
					.findOrderUserDetailResultMap();
			for (OrdersUserDetailPojo ordersUser : ordersUsers) {
				System.out.println(ordersUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * 使用resultMap和collection association进行多对多的映射
	 */
	@Test
	public void findUserAndItemsResultMap() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			OrderUserMapper orderUserMapper = sqlSession
					.getMapper(OrderUserMapper.class);
			List<UserToOrdersVo> ordersUsers = orderUserMapper
					.findUserAndItemsResultMap();
			for (UserToOrdersVo ordersUser : ordersUsers) {
				System.out.println(ordersUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}

	/**
	 * 延时加载
	 */
	@Test
	public void findOrderUserLazyLoading() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			OrderUserMapper orderUserMapper = sqlSession
					.getMapper(OrderUserMapper.class);
			List<OrdersUserPojo> ordersUsers = orderUserMapper
					.findOrderUserLazyLoading();
			for (OrdersUserPojo ordersUser : ordersUsers) {
				System.out.println(ordersUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}
	}
	
	/**
	 * 测试二级缓存
	 * @throws IOException 
	 */
	@Test
	public void testCache() throws IOException{
		SqlSession sqlSession=SqlSessionUtil.getSqlSessionFactory("mybatis-conf.xml").openSession();
		OrderUserMapper mapper=sqlSession.getMapper(OrderUserMapper.class);
		System.out.println("第一次查询订单用户");
		List<OrdersUser> ordersUsers=mapper.findOrdersUserByResultType();
		for (OrdersUser ordersUser : ordersUsers) {
			System.out.println(ordersUser);
		}
		//关闭一级缓存
		sqlSession.close();
		//如果未使用二级缓存 此时再次查询 会输出查询语句
		sqlSession=SqlSessionUtil.getSqlSessionFactory("mybatis-conf.xml").openSession();
		mapper=sqlSession.getMapper(OrderUserMapper.class);
		System.out.println("第二次查询");
		ordersUsers=mapper.findOrdersUserByResultType();
		for (OrdersUser ordersUser : ordersUsers) {
			System.out.println(ordersUser);
		}
		sqlSession.close();
	}
}



开缓存和延时加载配置

<!-- mybatis运行时全局参数配置 -->
	<settings>
		<setting name="cacheEnabled" value="true"></setting>
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 按需加载每个懒加载属性 -->
		<setting name="aggressiveLazyLoading" value="false" />
	</settings>

剩下的除了和前一篇博客一样外  还有一些POJO

package com.undergrowth.mybatis.po;

import java.io.Serializable;
import java.util.Date;

public class OrdersUser extends Orders implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private Date birthday;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return super.toString() + "[username=" + username + ", birthday="
				+ birthday + "]";
	}
}

package com.undergrowth.mybatis.po;

public class OrdersUserPojo extends Orders {
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String toString() {
		return super.toString() + "OrdersUserPojo [user=" + user + "]";
	}

}

package com.undergrowth.mybatis.po;

import java.util.List;

public class UserToOrdersVo extends User {
	private List<OrdersToOrderDetailVo> orderList;

	public List<OrdersToOrderDetailVo> getOrderList() {
		return orderList;
	}

	public void setOrderList(List<OrdersToOrderDetailVo> orderList) {
		this.orderList = orderList;
	}

	@Override
	public String toString() {
		return super.toString()+"UserToOrdersVo [orderList=" + orderList + "]";
	}
	
}

package com.undergrowth.mybatis.po;

import java.util.List;

public class OrdersToOrderDetailVo extends Orders {
	private List<OrderDetailToItems> orderDetailList;

	public List<OrderDetailToItems> getOrderDetailList() {
		return orderDetailList;
	}

	public void setOrderDetailList(List<OrderDetailToItems> orderDetailList) {
		this.orderDetailList = orderDetailList;
	}

	@Override
	public String toString() {
		return super.toString() + "OrdersToOrderDetailVo [orderDetailList="
				+ orderDetailList + "]";
	}

}


package com.undergrowth.mybatis.po;

public class OrderDetailToItems extends OrderDetail {
	private Items items;

	public Items getItems() {
		return items;
	}

	public void setItems(Items items) {
		this.items = items;
	}

	@Override
	public String toString() {
		return super.toString() + "OrderDetailToItems [items=" + items + "]";
	}

}




代码在github上 https://github.com/undergrowthlinear/learn/tree/master/mybatis





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值