在一个model类中,有时需要封装的属性不只有对应表中的字段,还需要其他model类中的模型,其使用示例如下:
property表示的实体类中属名
colum表示sql语句查询字段名(如果查询字段没有起别名,即是数据库字段名)
mapper类:
public interface UserMapper {
public Orders findOrderById2(int id);
}
xml配置:
<!--一对一-->
<!--如果模型里有模型,使用resultMap-->
<resultMap id="orderRslMap" type="orders">
<!--往orders的模型匹配数据-->
<id column="id" property="id"></id>
<id column="note" property="note"></id>
<id column="number" property="number"></id>
<id column="createtime" property="createtime"></id>
<!--往orders的user匹配数据-->
<association property="user" javaType="user">
<id column="user_id" property="id"></id>
<id column="username" property="username"></id>
<id column="address" property="address"></id>
</association>
</resultMap>
<select id="findOrderById2" parameterType="int" resultMap="orderRslMap">
select o.*, u.username, u.address, od.id detail_id, od.items_id, od.items_num
from orders o, user u, orderdetail od
where o.user_id = u.id and o.id = od.orders_id and o.id = #{id}
</select>
测试类:
public class Demo01 {
SqlSession session;
@Before
public void before() throws IOException {
System.out.println("before....获取session");
//读取配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//通过SqlSessionFactoryBuilder创建SqlSessionFactory会话工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//通过SqlSessionFactory创建SqlSession
session = sessionFactory.openSession();
}
@After
public void after(){
session.close();
}
//一对一,模型中有模型
@Test
public void test7() throws IOException {
OrderMapper mapper = session.getMapper(OrderMapper.class);
Orders order = mapper.findOrderById2(3);
System.out.println(order);
System.out.println(order.getUser());
}
}