Mybatis多表關聯查詢

一對一關係
比如住戶和地址是一對一的

//省略setter/getter

public class Address {
    private Long id;
    private String province;
    private String city;
}

public class Car {
    private Long id;
    private String color;
    private String name;
    //用戶id
    private Long userId;
}

public class User {
    private Long id;
    //地址信息,和用戶是一對一的關係
    private Address address;
    //地址id
    private Long addressId;
    //用戶擁有的車,和用戶是一對多的關係
    private List<Car> cars;
}

住戶類裏面得有一個Adress類型的數據
通過select
地址id查詢地址

public interface AddressRepository {
    /**
     * 根據地址id查詢地址
     */
    @Select("SELECT * FROM `address` WHERE id = #{id}")
    Address findAddressById(Long id);
}

通過這樣查找到的用戶是沒有住址的
那麼我們要把user中的addressId傳遞給AddressRepository的查詢地址的方法,
然後把查詢出的地址對象address賦值給user的address屬性,那麼我們怎麼做呢?

public interface UserRepository {
    @Select("SELECT * FROM `user` where id = #{id}")
    User findUserWithAddress(Long id);
}
用這樣的方法就可以了
查找到的user是有adress對象的
```java
public interface UserRepository {
    @Select("SELECT * FROM `user` where id = #{id}")
    @Results({
            @Result(property = "address", column = "address_id",
                    one = @One(select = "com.kingboy.repository.address.AddressRepository.findAddressById"))
    })
    User findUserWithAddress(Long id);
}

把user中的adress對象的adress的id去做地址的查詢,最後在做住戶的查詢,這樣的住戶就有adress對象了

同樣的一對多也是和麼個原理

只不過住戶多了一個車的列表(看上面給出的實體類)

public interface CarRepository {
    /**
     * 根據用戶id查詢所有的車
     */
    @Select("SELECT * FROM `car` WHERE user_id = #{userId}")
    List<Car> findCarByUserId(Long userId);
}

然後是

public interface UserRepository {
    /**
     * 查詢帶有車信息的用戶===============演示一對多(關於多對多其實就是兩個一對多組成)
     */
    @Select("SELECT * FROM `user` WHERE id = #{id}")
    @Results({
            @Result(property = "cars", column = "id",
                    many = @Many(select = "com.kingboy.repository.car.CarRepository.findCarByUserId"))
    })
    User getUserWithCar(Long id);
}

這就是一對多和多對多的查詢,理解後就很簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章