Mybatis多表查詢-一對一查詢
阿新 • • 發佈:2021-12-16
一對一查詢
使用者表和訂單表的關係為,一個使用者有多個訂單,一個訂單隻從屬於一個使用者,一對一查詢的需求:查詢一個訂單,與此同時查詢出該訂單所屬的使用者
對應的sql語句:select * from orders o,user u where o.uid=u.id;
1)建立Order和User實體
public class Order { private int id; private Date ordertime; private double total; //代表當前訂單從屬於哪一個客戶 private User user; } public class User { private int id; private String username; private String password; private Date birthday; }
2)建立OrderMapper介面
public interface OrderMapper {
List<Order> findAll();
}
3)配置OrderMapper.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"> <mapper namespace="com.itheima.mapper.OrderMapper"> <resultMap id="orderMap" type="order"> <!--手動指定欄位與實體屬性的對映關係 column: 資料表的欄位名稱 property:實體的屬性名稱 --> <id column="oid" property="id"></id> <result column="ordertime" property="ordertime"></result> <result column="total" property="total"></result> <!--<result column="uid" property="user.id"></result> <result column="username" property="user.username"></result> <result column="password" property="user.password"></result> <result column="birthday" property="user.birthday"></result>--> <!-- property: 當前實體(order)中的屬性名稱(private User user) javaType: 當前實體(order)中的屬性的型別(User) --> <association property="user" javaType="user"> <id column="uid" property="id"></id> <result column="username" property="username"></result> <result column="password" property="password"></result> <result column="birthday" property="birthday"></result> </association> </resultMap> <select id="findAll" resultMap="orderMap"> SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id </select> </mapper>
4)測試查詢結果
@Test public void test1() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); OrderMapper mapper = sqlSession.getMapper(OrderMapper.class); List<Order> orderList = mapper.findAll(); for (Order order : orderList) { System.out.println(order); } sqlSession.close(); }