一对一查询,先来理解什么是一对一查询(在mybatis中把多对一也看做成一对一),像商品和用户的关系,一个用户对应多个商品,一个商品仅供一个用户购买,他们之间用主键和外键来关联,一对一中,通过商品的外键来查找用户的信息。
此时我们会发现一个新注解@One 这是代表 一对一查询 里面的属性有select 用于指定 查找用户信息的方法(此时必须通过主键查找)fetchType 用于指定延时加载 LAZY表示延时加载 EAGER表示立即加载,在一对一中一般使用EAGER立即加载
package com.qst.dao;
import com.qst.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IAccountDao {
@Select("select * from Account")
@Results( id = "resultMap", value = {
@Result(column = "id" , property = "id", id = true),
@Result(column = "money",property = "money"),
@Result(column = "uid",property = "uid"),
@Result(property = "user",column = "uid" ,one=@One(select = "com.qst.dao.IUserDao.findById",fetchType = FetchType.EAGER))
})
List<Account> selectAll();
}
package com.qst.dao;
import com.qst.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface IUserDao {
@Select(("select * from employee where id = #{id}"))
List<User> findById(Integer id);
}
一对多查询,跟一对一查询正好相反,一个用户可以购买多个商品,在查询时,会把多个商品查询出来,在商品中通过与商品外籍相对应的用户的主键来查询。
一对多查询中使用注解@Many 其中属性与一对一差不多,在一对多查询中一般使用LAZY延时加载
package com.qst.dao;
import com.qst.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IUserDao {
@Select("select * from employee")
@Results(id="resultMap", value = {
@Result(column = "id" , property = "userId" ,id=true),
@Result(column = "gender" ,property = "gender"),
@Result(column = "email",property = "email"),
@Result(column = "did",property = "did"),
@Result(property = "account",column = "id" ,
many = @Many(select = "com.qst.dao.IAccountDao.selectbyId",
fetchType = FetchType.LAZY))
})
List<User> findAll();
}
package com.qst.dao;
import com.qst.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
public interface IAccountDao {
@Select("select * from account where uid=#{userId}")
List<Account> selectbyId(Integer userId);
}
写完代码在运行的时候我报了这么一个错误 returned more than one row, where no more than one was expected
也就是该封装到集合中的数据 没有集合封装,于是我找了半天想到 既然一对多,那么查询结果就应有多个account对象,所以在user实体中,封装account需要用List集合封装
ok,问题解决!