Mybaits使用注解方式完成一对一,一对多和多对多

Mybaits使用注解方式完成一对一,一对多和多对多

1.新建项目导入依赖(方便测试,只导入了Mybatis和Mysql依赖)

    
    
    
      org.mybatis
      mybatis
      3.4.6
    

    
    
    
      mysql
      mysql-connector-java
      5.1.44
    
    
      mybatis_01
      mybatis_01
      1.0-SNAPSHOT
      compile
    
  

2.注解使用一对一

1.数据库新建2张表,分别为A_1和B_2表
2.项目新建实体类:

package com.zl.mode;

import com.zl.mode.B_2;

//这是A表
public class A_1 {
    private int aid;
    private String aname;
    private B_2 b_2;

    public A_1(String aname) {
        this.aname = aname;
    }

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public String getAname() {
        return aname;
    }

    public void setAname(String aname) {
        this.aname = aname;
    }

    public B_2 getB_2() {
        return b_2;
    }

    public void setB_2(B_2 b_2) {
        this.b_2 = b_2;
    }

    public A_1(int aid, String aname, B_2 b_2) {
        this.aid = aid;
        this.aname = aname;
        this.b_2 = b_2;
    }

    public A_1() {
    }
}

package com.zl.mode;

import com.zl.mode.A_1;

//这是B表
public class B_2 {
    private int bid;
    private String bnubm;
    private A_1 a_1;


    public B_2(int bid, String bnubm, A_1 a_1) {
        this.bid = bid;
        this.bnubm = bnubm;
        this.a_1 = a_1;
    }

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    public String getBnubm() {
        return bnubm;
    }

    public void setBnubm(String bnubm) {
        this.bnubm = bnubm;
    }

    public A_1 getA_1() {
        return a_1;
    }

    public void setA_1(A_1 a_1) {
        this.a_1 = a_1;
    }

    public B_2() {
    }
}

3.在java文件中新建mappen接口包,再新建A1mappen与B2mappen接口,在对应接口中直接编写需要的方法在方法上使用@Select("")=查询,@Insert("")=增加,@Update("")=修改,@Delete("")=删除

package com.zl.mappen;


import com.zl.mode.A_1;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

//Amappen接口
public interface Amapen {
    //查询A的同时,查询A对应B的信息
    @Select("select * from A_1 where aid=#{aid}")
    @Results({ //返回多个结果集
            @Result(property = "aid",column = "aid",id = true), //A表中的属性(必须标记ID,其他属性可不写)
            @Result(property = "b_2",column = "aid",one = @One(select ="com.zl.mappen.Bmapen.findBid"))//调用Bmapen中findBid方法,将aid传给这个方法
    })
    public A_1 findAID(int bid);
}

package com.zl.mappen;

import com.zl.mode.B_2;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

//Bmappen接口
public interface Bmapen {
	//查询B的同时,查询B对应A的信息
    @Select("select * from b_2 where bid=#{bid}")
    @Results({
            @Result(property = "bid",column = "bid",id = true),
            @Result(property = "a_1",column = "bid",one = @One(select ="com.zl.mappen.Amapen.findAID"))//调用Amapen中findAID方法,将bid传给这个方法

    })
    public B_2 findBid(int aid);
}

4.配置Mybatis.xml




    
    

    
    
        
            
            
                
                
                
                
            
        
    


    
        
        
       
    


进行测试:

package com.zl.test;

import com.zl.mappen.Amapen;
import com.zl.mode.A_1;
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;

public class ATest {

    private SqlSession session;

    @Before
    public void before(){
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(this.getClass().getClassLoader().getResourceAsStream("mybatis.xml"));
        session = factory.openSession();
    }

    @Test
    public void test(){
        //根据Aid查询A表,同时查询A对应B的信息
       Amapen amapen=session.getMapper(Amapen.class);
         A_1 a=amapen.findAID(2);
        System.out.println(a.getAname()+"\t"+a.getB_2().getBnubm());
    }

}

3.注解使用一对多与多对一

1.例子:书和作者(一位作者可以拥有多本书籍,一本书籍只能有一位作者)
2.新建表Book(书),Author(作者),再新建实体类:

package com.zl.mode;

import java.util.List;
//作者
public class Author {
    private Integer zid;
    private String zname;
    private List books;

    public Author(Integer zid, String zname, List books) {
        this.zid = zid;
        this.zname = zname;
        this.books = books;
    }

    public Integer getZid() {
        return zid;
    }

    public void setZid(Integer zid) {
        this.zid = zid;
    }

    public String getZname() {
        return zname;
    }

    public void setZname(String zname) {
        this.zname = zname;
    }

    public List getBooks() {
        return books;
    }

    public void setBooks(List books) {
        this.books = books;
    }

    public Author() {
    }
}
package com.zl.mode;
//书
public class Book {
    private Integer bid;
    private String bname;
    private Author zuoZe;

    public Book(Integer bid, String bname, Author zuoZe) {
        this.bid = bid;
        this.bname = bname;
        this.zuoZe = zuoZe;
    }

    public Integer getBid() {
        return bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public Author getZuoZe() {
        return zuoZe;
    }

    public void setZuoZe(Author zuoZe) {
        this.zuoZe = zuoZe;
    }

    public Book() {
    }
}

3.在mappen包中建入BookMappen接口与Authormappen接口

package com.zl.mappen;

import com.zl.mode.Book;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface BookMappen {
    //根据作者ID的找到书
    @Select("select * from book where zid=#{zid}")
    public Book findBookByID(int zid);

    //根据书的ID找到书籍信息和对应的作者信息

    @Select("select * from book where bid=#{bid}")
    @Results({
            @Result(property = "bid",column = "bid",id = true),
            @Result(property = "zuoZe",column = "zid",one = @One(select = "com.zl.mappen.AuthorMappen.findAuthorByBook"))
    })
    public Book findBookByAuth(int bid);
}

package com.zl.mappen;

import com.zl.mode.Author;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface AuthorMappen {
    //通过作者查询作者和作者的所有书
    @Select("select * from zuoze where zid=#{zid}")
    @Results({
            @Result(property = "zid",column = "zid",id = true),
            @Result(property = "books",column = "zid",many = @Many(select = "com.zl.mappen.BookMappen.findBookByID" ))//这里属于多的一方
    })
    public Author findAuthorByBook(int zid);

}

4.配置Mybatis.xml,进入Test类测试

package com.zl.test;

import com.zl.mode.Author;
import com.zl.mode.Book;
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.util.List;

public class AuthorTset {
    private SqlSession session;

    @Before
    public void before(){
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(this.getClass().getClassLoader().getResourceAsStream("mybatis.xml"));
        session = factory.openSession();
    }

    @Test
    public void test(){
        BookMappen bookMappen= session.getMapper(BookMappen.class);
        Book a=bookMappen.findBookByAuth(1);
        System.out.println("书籍:"+a.getBname()+"作者:"+a.getZuoZe().getZname());
    }
}

4.注解使用多对多

1.例子:老师与学生。
2.数据库新建表Student(学生表),Teacher(老师表),在项目新建实体类

package com.zl.mode;

import java.util.List;
//学生类
public class Sudent {
    private Integer sid;
    private String sname;
    private List teachers;

    public Sudent(Integer sid, String sname, List teachers) {
        this.sid = sid;
        this.sname = sname;
        this.teachers = teachers;
    }

    public Sudent() {
    }

    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;
    }

    public List getTeachers() {
        return teachers;
    }

    public void setTeachers(List teachers) {
        this.teachers = teachers;
    }
}

package com.zl.mode;

import java.util.List;
//老师类
public class Teacher {
    private Integer xid;
    private String xname;
    private List sudents;

    public Teacher(Integer xid, String xname, List sudents) {
        this.xid = xid;
        this.xname = xname;
        this.sudents = sudents;
    }

    public Teacher() {
    }

    public Integer getXid() {
        return xid;
    }

    public void setXid(Integer xid) {
        this.xid = xid;
    }

    public String getXname() {
        return xname;
    }

    public void setXname(String xname) {
        this.xname = xname;
    }

    public List getSudents() {
        return sudents;
    }

    public void setSudents(List sudents) {
        this.sudents = sudents;
    }
}

3.在mappen中新建StudentsMapper与TeacherMapper接口

package com.zl.mappen;

import com.zl.mode.Sudent;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

//StudentsMapper接口

public interface SudentMappen {
    //通过老师ID查询学生信息
    @Select("select * from student s left  join su_xx sx on s.sid=sx.sid where sx.xid=#{xid}")
    public Sudent findSudentID(int xid);

    @Select("select * from student where sid=#{sid}")
    @Results({
            @Result(property = "sid",column = "sid",id = true),
            @Result(property = "teachers",column = "sid",many = @Many(select = "com.zl.mappen.TeacherMappen.findTeacherID"))
    })
    //通过学生查询学生信息找到对应老师的信息
    public Sudent findStudentTec(int sid);
}

package com.zl.mappen;

import com.zl.mode.Sudent;
import com.zl.mode.Teacher;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface TeacherMappen {
    //通过老师ID查询学生信息
    @Select("select * from  xuexiao x left  join su_xx sx on x.xid=sx.xid where sx.sid=#{sid}")
    public Teacher findTeacherID(int sid);

    @Select("select * from xuexiao where xid=#{xid}")
    @Results({
            @Result(property = "xid",column = "xid",id = true),
            @Result(property = "sudents",column = "xid",many=@Many(select = "com.zl.mappen.SudentMappen.findSudentID"))
    })
    //通过老师ID查询老师信息,和对应老师所有的学生
    public Teacher findTeacherIDStu(int xid);

}

多对多与一对多差别不大,只是多对多有一张第三方表,在你需要查询某一方信息,同时查询对应的集合中所有信息时,只需将对应一方连接第三方表查询某一方表中的ID即可。

你可能感兴趣的:(Mybatis)