sql语句为:
select o.*,u.username,u.address from orders o join kuser u on o.user_id = u.id where o.id = 8; #要查询的字段根据需求来定,这里只需要查询用户的姓名和地址
OrdersMapper.xml:
<!--自定义映射--> <resultMap id="order_resultMap" type="com.kkb.pojo.Order"> <!--orders表映射--> <id column="id" property="id"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <!--关联的user表映射--> <association property="user" javaType="user"> <id column="user_id" property="id"/> <result column="username" property="name"/> <result column="address" property="address"/> </association> </resultMap> <select id="selectOrderByID" parameterType="int" resultMap="order_resultMap"> select o.*,u.username,u.address from orders o join kuser u on o.user_id = u.id where o.id = #{oid}; </select>
测试代码:
@Test public void test(){ SqlSession session = factory.openSession(); OrdersMapper mapper = session.getMapper(OrdersMapper.class);//记得提供映射接口 Order order = mapper.selectOrderByID(8); System.out.println(order); session.close(); }