MyBatis多表操作-----一对多操作
一对多相对于一对一有很多相似的地方,我们着重去说改动的地方
在向Father中链接Son值时,因为一对多的关系,需要放进List表中进行存储
private List<Son> sons=new ArrayList<>();
public List<Son> getSons() {
return sons;
}
public void setSons(List<Son> sons) {
this.sons = sons;
}
其中在一对一需要修改Mapper时,FatherMapper中
原本是@One注解要替换成@Many,因为此时son对于Father是一对多的关系
同时需要在SonMapper上面添加功能
@Results({
@Result(column="sid", property="sid", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER),
@Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
@Result(property = "father",column = "fid",one =
@One(select = "com.ryh.mapper.FatherMapper.selectByPrimaryKey"))
})
List<Son> selectSonsByFid(Integer fid);
public class FatherService {
private SqlSessionFactory ssf;
public FatherService() {
InputStream is=this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml");
ssf=new SqlSessionFactoryBuilder().build(is);
}
@Test
public void updateHus(){
SqlSession session = ssf.openSession();
try{
Hus hus = new Hus();
hus.setId(2);
hus.setHname("吉林");
session.update("com.ryh.test.mapper.HusMapper.updateByPrimaryKey",hus);
Wife wife = new Wife();
wife.setId(2);
wife.setWname("长春");
session.update("com.ryh.test.mapper.WifeMapper.updateByPrimaryKey",wife);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void deleteHus(){
SqlSession session = ssf.openSession();
try{
session.delete("com.ryh.test.mapper.WifeMapper.deleteByPrimaryKey",6);
session.delete("com.ryh.test.mapper.HusMapper.deleteByPrimaryKey",6);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void addHus(){
SqlSession session = ssf.openSession();
try{
Hus hus = new Hus();
hus.setHname("黄晓明");
session.insert("com.ryh.test.mapper.HusMapper.insert",hus);
Wife wife=new Wife();
wife.setId(hus.getId());
wife.setWname("杨颖");
session.insert("com.ryh.test.mapper.WifeMapper.insert",wife);
session.commit();
}catch (Exception e){
session.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void queryFather(){
SqlSession session=ssf.openSession();
FatherExample fatherExample=new FatherExample();
List<Father>list=session.selectList("com.ryh.test.mapper.FatherMapper.selectByExample",fatherExample);
list.forEach(f->{
if(f.getSons().size()==0){
System.out.println(f.getFname());
}else{
List<Son>sons=new ArrayList<>();
System.out.println(f.getFname()+"----");
sons.forEach(s-> System.out.println(s.getSname()+",\t"));
System.out.println("");
}
});
session.close();
}
@Test
public void querySon(){
SqlSession session = ssf.openSession();
SonExample example=new SonExample();
List<Son> list =session.selectList("com.ryh.test.mapper.SonMapper.selectByExample",example);
list.forEach(s->{
System.out.println(s.getSname()+"----"+s.getFather().getFname());
});
session.close();
}
}