本文主要是介绍MyBatis注解之多对多,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、ProductMapper
public interface ProductMapper {@Select("select * from product_ where id = #{id}")public Product get(int id);
}
2、OrderItemMapper
提供listByOrder方法,与Product建立多对一关系。
public interface OrderItemMapper {@Select(" select * from order_item_ where oid = #{oid}")@Results({ @Result(property="product",column="pid",one=@One(select="com.how2java.mapper.ProductMapper.get")) }) public List<OrderItem> listByOrder(int oid);
}
3、OrderMapper
提供list方法,与OrderItem建立一对多关系。
public interface OrderMapper {@Select("select * from order_")@Results({@Result(property = "id", column = "id"),@Result(property = "orderItems", javaType = List.class, column = "id", many = @Many(select = "com.how2java.mapper.OrderItemMapper.listByOrder"))}) public List<Order> list();
}
4、mybatis-config.xml
<mapper class="com.how2java.mapper.OrderItemMapper"/><mapper class="com.how2java.mapper.OrderMapper"/><mapper class="com.how2java.mapper.ProductMapper"/>
5、Test类
public class TestMybatis {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();listOrder(session);session.commit();session.close();}private static void listOrder(SqlSession session) {OrderMapper mapper =session.getMapper(OrderMapper.class);List<Order> os = mapper.list();for (Order o : os) {System.out.println(o.getCode());List<OrderItem> ois= o.getOrderItems();if(null!=ois){for (OrderItem oi : ois) {System.out.format("\t%s\t%f\t%d%n", oi.getProduct().getName(),oi.getProduct().getPrice(),oi.getNumber());} }}}
}
这篇关于MyBatis注解之多对多的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!