欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis的数据库一对一 ,一对多,和多对多的关系

程序员文章站 2022-04-22 08:00:24
...

Mybatis连接数据库有两种方式

通过Mybatis****的方法生成的生成的方式中XML比注解方式多一个mapping,总体来看注解方式更由于XML方式。

  • XML方式
  • 注解方式

XML方式

  1. 首先需要在资源里的Mybatis.cfg.xml里面加入需要的的mapper。
  2. 将mapping下的xml文档也移动到资源里面
  3. 在service层创建进行方的实现

实现如下

见我上篇文章初始Mybatis里面的例子就是通过xml方式实现的,本篇主要介绍通过注释的方式来实现数据库中一对一 ,一对多,和多对多的关系和后端的联系
点击此处跳往上篇

注解方式

  1. 首先需要在资源里的Mybatis.cfg.xml里面加入需要的的mapper。
  2. 进行****导入需要的mapper层和model层

数据库中的一对一关系

配置文档

    SqlSessionFactory ssf=null;
    @Before
    public void init(){
        InputStream ios=this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml");
        ssf=new SqlSessionFactoryBuilder().build(ios);

    }

数据的增加

HusMapper:

    @Insert({
        "insert into hus (id, hname)",
        "values (#{id,jdbcType=INTEGER}, #{hname,jdbcType=VARCHAR})"
    })
     @Options(keyColumn = "id",keyProperty = "id",useGeneratedKeys = true)//为真自动加一   主要是针对insert有效,
     //当有关联表操作的时候,可以先插入主表,然后根据主表返回的主键id去落库详情表
    int insert(Hus record);

service层:

    @Test
    public void add(){
        SqlSession sqlSession=ssf.openSession();
        try{

            Hus hus=new Hus();
            hus.setHname("ADSON");
            sqlSession.insert("com.ruigr.mapper.HusMapper.insert",hus);

            Wife wife=new Wife();
            wife.setId(hus.getId());
            wife.setWname("MARY");
            sqlSession.insert("com.ruigr.mapper.WifeMapper.insert",wife);
            sqlSession.commit();

        }catch(Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }

数据的更新

HusMapper:

    @Update({
        "update hus",
        "set hname = #{hname,jdbcType=VARCHAR}",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(Hus record);

service层:

    @Test
    public void update(){
        SqlSession sqlSession=ssf.openSession();
        try{
            Hus hus=new Hus();
            hus.setId(3);
            hus.setHname("herbin");
            sqlSession.update("com.ruigr.mapper.HusMapper.updateByPrimaryKey",hus);

            sqlSession.commit();

        }catch(Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }

数据的删除

在删除过程中首先要删除从表,在删除主表
service层:

 @Test
    public void del(){
        SqlSession sqlSession=ssf.openSession();
        try{

            sqlSession.delete("com.ruigr.mapper.WifeMapper.deleteByPrimaryKey",4);
            sqlSession.delete("com.ruigr.mapper.HusMapper.deleteByPrimaryKey",4);
            sqlSession.commit();

        }catch(Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }
    

HusMapper:

    @Delete({
        "delete from hus",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer id);

数据的查询,

  • 第一种是通过丈夫查询唯一的妻子第二种是通过妻子查询唯一的丈夫。
  • 首先在model层在Hus里添加属性Wife,压在wife里添加属性Hus

Hus

public class Hus {
    private Integer id;
     private Wife wife;

    public Wife getWife() {
        return wife;
    }

    public void setWife(Wife wife) {
        this.wife = wife;
    }

    private String hname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getHname() {
        return hname;
    }

    public void setHname(String hname) {
        this.hname = hname == null ? null : hname.trim();
    }
}

Wife

public class Wife {
    private Integer id;
    private Hus hus;

    public Hus getHus() {
        return hus;
    }

    public void setHus(Hus hus) {
        this.hus = hus;
    }

    private String wname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getWname() {
        return wname;
    }

    public void setWname(String wname) {
        this.wname = wname == null ? null : wname.trim();
    }
}
  • 然后需要在mapper层进行建立一对一的关系

HusMapper:

    @SelectProvider(type=HusSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="hname", property="hname", jdbcType=JdbcType.VARCHAR),
            @Result(column="id", property="wife",
                    one=@One(select = "com.ruigr.mapper.WifeMapper.selectByPrimaryKey"))
    })
    List<Hus> selectByExample(HusExample example);

WifeMapper

    @SelectProvider(type=WifeSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="wname", property="wname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "hus",column = "id",
                    one = @One(select = "com.ruigr.mapper.HusMapper.selectByPrimaryKey"))
    })
    List<Wife> selectByExample(WifeExample example);

service层:

@Test
    public void queryAllWife(){

        SqlSession sqlSession=ssf.openSession();
        try{
            WifeExample example=new WifeExample();
            List<Wife> list=sqlSession.selectList("com.ruigr.mapper.WifeMapper.selectByExample",example);
            list.forEach(c->System.out.println(c.getWname()+"-----"+c.getHus().getHname()));
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }
    @Test
    public void queryAllHus(){
        SqlSession sqlSession=ssf.openSession();
        try{
            HusExample example=new HusExample();

            List<Hus> list=sqlSession.selectList("com.ruigr.mapper.HusMapper.selectByExample",example);

            list.forEach(c->System.out.println(c.getHname()+"----"+c.getWife().getWname()));

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }

数据库中的一对多关系

mapper层:

sons:

package com.ruigr.mapper;

import com.ruigr.model.Sons;
import com.ruigr.model.SonsExample;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;

public interface SonsMapper {
    @SelectProvider(type=SonsSqlProvider.class, method="countByExample")
    long countByExample(SonsExample example);

    @DeleteProvider(type=SonsSqlProvider.class, method="deleteByExample")
    int deleteByExample(SonsExample example);

    @Delete({
        "delete from sons",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer id);

    @Insert({
        "insert into sons (id, sname, ",
        "fid)",
        "values (#{id,jdbcType=INTEGER}, #{sname,jdbcType=VARCHAR}, ",
        "#{fid,jdbcType=INTEGER})"
    })
    int insert(Sons record);

    @InsertProvider(type=SonsSqlProvider.class, method="insertSelective")
    int insertSelective(Sons record);

    @SelectProvider(type=SonsSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
        @Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER)
    })
    List<Sons> selectByExample(SonsExample example);

    @Select({
        "select",
        "id, sname, fid",
        "from sons",
        "where id = #{id,jdbcType=INTEGER}"
    })
    @Results({
        @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
        @Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER)
    })
    Sons selectByPrimaryKey(Integer id);

    @Select({
            "select",
            "id, sname, fid",
            "from sons",
            "where fid = #{id,jdbcType=INTEGER}"
    })
    @Results({
            @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
            @Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER)
    })
    List<Sons> selectSonsForFid(Integer fid);

    @UpdateProvider(type=SonsSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") Sons record, @Param("example") SonsExample example);

    @UpdateProvider(type=SonsSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") Sons record, @Param("example") SonsExample example);

    @UpdateProvider(type=SonsSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(Sons record);

    @Update({
        "update sons",
        "set sname = #{sname,jdbcType=VARCHAR},",
          "fid = #{fid,jdbcType=INTEGER}",
        "where id = #{id,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(Sons record);
}

father:

package com.ruigr.mapper;

import com.ruigr.model.Father;
import com.ruigr.model.FatherExample;
import java.util.List;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

public interface FatherMapper {
    @SelectProvider(type=FatherSqlProvider.class, method="countByExample")
    long countByExample(FatherExample example);

    @DeleteProvider(type=FatherSqlProvider.class, method="deleteByExample")
    int deleteByExample(FatherExample example);

    @Delete({
        "delete from father",
        "where fid = #{fid,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer fid);

    @Insert({
        "insert into father (fid, fname)",
        "values (#{fid,jdbcType=INTEGER}, #{fname,jdbcType=VARCHAR})"
    })
    int insert(Father record);

    @InsertProvider(type=FatherSqlProvider.class, method="insertSelective")
    int insertSelective(Father record);

    @SelectProvider(type=FatherSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="fname", property="fname", jdbcType=JdbcType.VARCHAR),
    })
    List<Father> selectByExample(FatherExample example);

    @Select({
        "select",
        "fid, fname",
        "from father",
        "where fid = #{fid,jdbcType=INTEGER}"
    })
    @Results({
        @Result(column="fid", property="fid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="fname", property="fname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "list",column = "fid",
                    one = @One(select = "com.ruigr.mapper.SonsMapper.selectSonsForFid"))
    })
    Father selectByPrimaryKey(Integer fid);

    @UpdateProvider(type=FatherSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") Father record, @Param("example") FatherExample example);

    @UpdateProvider(type=FatherSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") Father record, @Param("example") FatherExample example);

    @UpdateProvider(type=FatherSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(Father record);

    @Update({
        "update father",
        "set fname = #{fname,jdbcType=VARCHAR}",
        "where fid = #{fid,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(Father record);
}

model层:

  • Father
package com.ruigr.model;

import java.util.List;

public class Father {
    private Integer fid;
    private List<Sons> list;
    private String fname;

    public List<Sons> getList() {
        return list;
    }

    public void setList(List<Sons> list) {
        this.list = list;
    }

    public Integer getFid() {
        return fid;
    }

    public void setFid(Integer fid) {
        this.fid = fid;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname == null ? null : fname.trim();
    }
}
  • Sons
package com.ruigr.model;

public class Sons {
    private Integer id;

    private String sname;

    private Integer fid;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname == null ? null : sname.trim();
    }

    public Integer getFid() {
        return fid;
    }

    public void setFid(Integer fid) {
        this.fid = fid;
    }
}

Service层:

package com.ruigr.Service;

import com.ruigr.model.Father;
import com.ruigr.model.Sons;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;

public class FatherServiceImpl {
    SqlSessionFactory ssf=null;
    @Before
    public void init(){
        InputStream ios=this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml");
        ssf=new SqlSessionFactoryBuilder().build(ios);

    }

    @Test
    public void del(){
        SqlSession sqlSession=ssf.openSession();
        try{

            sqlSession.delete("com.ruigr.mapper.SonsMapper.deleteByPrimaryKey",9);
            sqlSession.delete("com.ruigr.mapper.FatherMapper.deleteByPrimaryKey",9);
            sqlSession.commit();

        }catch(Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }

    @Test
    public void addFather(){

        SqlSession sqlSession=ssf.openSession();
        try{

            Father f=new Father();
            f.setFname("HLJ5");
            sqlSession.insert("com.ruigr.mapper.FatherMapper.insert",f);

            Sons s1=new Sons();
            s1.setSname("hlg5");
            s1.setFid(f.getFid());

            Sons s=new Sons();
            s.setSname("许府路55");
            s.setFid(f.getFid());

            sqlSession.insert("com.ruigr.mapper.SonsMapper.insert",s);
            sqlSession.insert("com.ruigr.mapper.SonsMapper.insert",s1);
            sqlSession.commit();

        }catch(Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }

    }

    @Test
    public void queryFather(){
        SqlSession sqlSession=ssf.openSession();
        try{

            Father f=sqlSession.selectOne("com.ruigr.mapper.FatherMapper.selectByPrimaryKey",1);
            System.out.println(f.getFname()+"的儿子");

            f.getList().forEach(c->System.out.println(c.getSname()));


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }


}

解释:

  • 增加时:需要先增加主类后增加副类
  • 删除时:需要先删除副类后删除主类
  • 查询时:需要在nodel层里的father中加入一个只能加Sons的泛型集合。通过id进行查询,但是在SonsMapper里面没有selectSonsForFid。所以需要自己通过在上下文中的相似代码进行照猫画虎。注意返回的是多组,所以要采用集合的方式。

数据库中多对多的关系

mapper层:
stumapper:

package com.ruigr.mapper;

import com.ruigr.model.Stu;
import com.ruigr.model.StuExample;
import java.util.List;

import com.ruigr.model.Tea;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

public interface StuMapper {
    @SelectProvider(type=StuSqlProvider.class, method="countByExample")
    long countByExample(StuExample example);

    @DeleteProvider(type=StuSqlProvider.class, method="deleteByExample")
    int deleteByExample(StuExample example);

    @Delete({
        "delete from stu",
        "where sid = #{sid,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer sid);

    @Insert({
        "insert into stu (sid, sname)",
        "values (#{sid,jdbcType=INTEGER}, #{sname,jdbcType=VARCHAR})"
    })
    int insert(Stu record);

    @InsertProvider(type=StuSqlProvider.class, method="insertSelective")
    int insertSelective(Stu record);

    @SelectProvider(type=StuSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="sid", property="sid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR)
    })
    List<Stu> selectByExample(StuExample example);

    @Select({
            "select",
            "sid, sname",
            "from stu",
            "where sid = #{sid,jdbcType=INTEGER}"
    })
    @Results({
            @Result(column="sid", property="sid", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "teas",column = "sid",
                    many = @Many(select = "com.ruigr.mapper.TeaMapper.selectTeasBySid"))
    })
    Stu selectByPrimaryKey(Integer sid);


    @Select({
            "SELECT  ",
            "sid, sname ",
            "FROM stu ",
            "WHERE sid in ",
            " (SELECT sid ",
            " FROM teastu ",
            " WHERE tid=#{tid,jdbcType=INTEGER}) "
    })
    @Results({
            @Result(column="sid", property="sid", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="sname", property="sname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "teas",column = "sid",
                    many = @Many(select = "com.ruigr.mapper.TeaMapper.selectTeasBySid"))
    })
    List<Stu> selectStusByTid(Integer tid);



    @UpdateProvider(type=StuSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") Stu record, @Param("example") StuExample example);

    @UpdateProvider(type=StuSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") Stu record, @Param("example") StuExample example);

    @UpdateProvider(type=StuSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(Stu record);

    @Update({
        "update stu",
        "set sname = #{sname,jdbcType=VARCHAR}",
        "where sid = #{sid,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(Stu record);
}

TeaMapper:

package com.ruigr.mapper;

import com.ruigr.model.Tea;
import com.ruigr.model.TeaExample;
import java.util.List;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

public interface TeaMapper {
    @SelectProvider(type=TeaSqlProvider.class, method="countByExample")
    long countByExample(TeaExample example);

    @DeleteProvider(type=TeaSqlProvider.class, method="deleteByExample")
    int deleteByExample(TeaExample example);

    @Delete({
        "delete from tea",
        "where tid = #{tid,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer tid);

    @Insert({
        "insert into tea (tid, tname)",
        "values (#{tid,jdbcType=INTEGER}, #{tname,jdbcType=VARCHAR})"
    })
    int insert(Tea record);

    @InsertProvider(type=TeaSqlProvider.class, method="insertSelective")
    int insertSelective(Tea record);

    @SelectProvider(type=TeaSqlProvider.class, method="selectByExample")
    @Results({
        @Result(column="tid", property="tid", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="tname", property="tname", jdbcType=JdbcType.VARCHAR)
    })
    List<Tea> selectByExample(TeaExample example);


    @Select({
            "SELECT  ",
            "tid, tname ",
            "FROM tea ",
            "WHERE tid in ",
            " (SELECT tid ",
            " FROM teastu ",
            " WHERE sid=#{sid,jdbcType=INTEGER}) "
    })
    @Results({
            @Result(column="tid", property="tid", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="tname", property="tname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "stus",column = "tid",
                    many = @Many(select = "com.ruigr.mapper.StuMapper.selectStusByTid"))
    })
    List<Tea> selectTeasBySid(Integer sid);



    @Select({
            "select",
            "tid, tname",
            "from tea",
            "where tid = #{tid,jdbcType=INTEGER}"
    })
    @Results({
            @Result(column="tid", property="tid", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="tname", property="tname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "stus",column = "tid",
                    many = @Many(select = "com.ruigr.mapper.StuMapper.selectStusByTid"))
    })
    Tea selectByPrimaryKey(Integer tid);

    @UpdateProvider(type=TeaSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") Tea record, @Param("example") TeaExample example);

    @UpdateProvider(type=TeaSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") Tea record, @Param("example") TeaExample example);

    @UpdateProvider(type=TeaSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(Tea record);

    @Update({
        "update tea",
        "set tname = #{tname,jdbcType=VARCHAR}",
        "where tid = #{tid,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(Tea record);
}

model层:
Tea

package com.ruigr.model;

import java.util.List;

public class Tea {
    private Integer tid;
private List<Stu> stus;
    private String tname;

    public List<Stu> getStus() {
        return stus;
    }

    public void setStus(List<Stu> stus) {
        this.stus = stus;
    }

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname == null ? null : tname.trim();
    }
}

Stu:

package com.ruigr.model;

import java.util.List;

public class Stu {
    private Integer sid;
private List<Tea> teas;
    private String sname;

    public List<Tea> getTeas() {
        return teas;
    }

    public void setTeas(List<Tea> teas) {
        this.teas = teas;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname == null ? null : sname.trim();
    }
}

service层:

package com.ruigr.Service;

import com.ruigr.model.Father;
import com.ruigr.model.Stu;
import com.ruigr.model.Tea;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;

public class TeaServiceImpl {
    SqlSessionFactory ssf=null;
    @Before
    public void init(){
        InputStream ios=this.getClass().getClassLoader().getResourceAsStream("mybatis.cfg.xml");
        ssf=new SqlSessionFactoryBuilder().build(ios);

    }
    @Test
    public void queryTea(){
        SqlSession sqlSession=ssf.openSession();
        try{
            Tea f=sqlSession.selectOne("com.ruigr.mapper.TeaMapper.selectByPrimaryKey",1);
            System.out.println(f.getTname()+"的学生有");
            f.getStus().forEach(c->System.out.println(c.getSname()));
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }
    @Test
    public void queryStu(){
        SqlSession sqlSession=ssf.openSession();
        try{

            Stu f=sqlSession.selectOne("com.ruigr.mapper.StuMapper.selectByPrimaryKey",1);

            System.out.println(f.getSname()+"的老师 有:");

            f.getTeas().forEach(c->System.out.println(c.getTname()));


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }



    @Test
    public void queryTea1(){
        SqlSession sqlSession=ssf.openSession();
        try{

            Tea f=sqlSession.selectOne("com.ruigr.mapper.TeaMapper.selectByPrimaryKey",1);

            System.out.println("-----"+f.getTname());

            f.getStus().forEach(c->{
                System.out.println(c.getSname());
                c.getTeas().forEach(
                        c1->System.out.println(">>>>"+c1.getTname())
                );

            });


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }
    }
}

解释:这里用到了子查询,需要在外面把SQL语句写好后,在按照照猫画虎放在被查找的mapper里面(例:当通过老师找学生时就放在学生里面)

  • 第一种查询和第二种查询时基本一致的,只不过是一个是通过老师查询学生,另一个是通过学生查找老师。
  • 最后一个是在老师查询学生的过程中再次通过查询学生找到对应的老师(充分体现数据库多对多的关系)实现就是在被查询中再进行查询,如下:
    @Select({
            "SELECT  ",
            "tid, tname ",
            "FROM tea ",
            "WHERE tid in ",
            " (SELECT tid ",
            " FROM teastu ",
            " WHERE sid=#{sid,jdbcType=INTEGER}) "
    })
    @Results({
            @Result(column="tid", property="tid", jdbcType=JdbcType.INTEGER, id=true),
            @Result(column="tname", property="tname", jdbcType=JdbcType.VARCHAR),
            @Result(property = "stus",column = "tid",
                    many = @Many(select = "com.ruigr.mapper.StuMapper.selectStusByTid"))
    })
    List<Tea> selectTeasBySid(Integer sid);

例子:

  • 老师:张三
    • 学生:哈哈
      • 老师:张三
      • 老师:里斯
    • 学生:嘿嘿
      • 老师:张三
      • 老师:里斯