junit测试类代码:(调用接口)
private SqlSessionFactory ssf = null;
@Before
public void before() throws Exception {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
this.ssf = new SqlSessionFactoryBuilder().build(is);
}
@Test
public void aaa() {
SqlSession sqlSession = this.ssf.openSession();
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Orders> orders = mapper.selectAllOrdersWithUser();
for (Orders order :
orders) {
System.out.println(order);
}
}
接口mapper类代码:
/**
* Created by syk on 2018/2/16.
*/
public interface OrderMapper {
public List<Orders> selectAllOrders();
//多对一
public List<Orders> selectAllOrdersWithUser();
}
接口对应的xml文件代码:
<?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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="cn.itcast.mapper.OrderMapper">
<resultMap id="ordersList" type="Orders">
<result property="user_id" column="userId"></result>
</resultMap>
<select id="selectAllOrders" resultMap="ordersList">
SELECT id,user_id,number,createtime,note FROM orders
</select>
<resultMap id="allOrdersWithUser" type="Orders">
<result column="user_id" property="userId"/>
<result column="id" property="id"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<association property="user" javaType="User">
<result column="user_id" property="id"/>
<result column="username" property="username"/>
</association>
</resultMap>
<select id="selectAllOrdersWithUser" resultMap="allOrdersWithUser">
select
o.*,
u.*
from orders o
LEFT JOIN user u
on o.user_id = u.id;
</select>
网友评论