SpringBoot+Mybatis实现关联查询
今天学习了下Mybatis的动态查询,然后接着上次的Demo改造了下实现表的关联查询。
话不多说,开始今天的小Demo
首先接着上次的项目 https://www.cnblogs.com/Leslie-/p/9469045.html
然后呢我们在数据库中创建新的两张表
如下图所示:
然后呢,关联查询当然要在User表里面添加新的属性
接下来 在项目中添加Car的实体类以及address的实体类
package com.example.demo.entity;
/**
* author:lrh
* Date:2018/8/15
* Time:14:08
*/
public class Address {
private Integer id;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.example.demo.entity;
/**
* author:lrh
* Date:2018/8/15
* Time:14:23
*/
public class Car {
private Integer id;
private String color;
private String car;
private Integer userid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
}
还有就是得添加下User实体类的属性
添加如下:
创建CarMapper和AddressMapper
再CarMapper里面添加selectAllCar的方法以及注解
@Repository @Mapper public interface CarMapper { @Select("SELECT * FROM car WHERE userid = #{userid}") public List<Car> selectAllCar(); }
AddressMapper里面添加select的方法以及注解
@Repository
@Mapper
public interface AddressMapper {
@Select("SELECT * FROM address WHERE id = #{id}")
public Address selectByID(Integer id);
}
最后再UserMapper里面调用,在下比较懒就懒得新写了,直接在原先的selectByPrimaryKey方法上面加了。。
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "address" ,column = "addressid",
one = @One(select = "com.example.demo.dao.AddressMapper.selectByID")),
@Result(property = "cars" ,column = "id",
many = @Many(select = "com.example.demo.dao.CarMapper.selectAllCar"))
//column代表将该属性作为参数传入,property代表将查询出来的数据交给该属性
})
User selectByPrimaryKey(Integer id);
最后启动DemoAppliction
嗯。。大功告成。。告辞告辞