mybatis的接口绑定方式(注解绑定和配置xml文件)

目录

一、配置xml文件

步骤

1、创建pojo类(Student对象)

 2、创建StudentMapper接口

 3、创建mapper.xml配置文件

 4、在mymybatis-config.xml中添加StudentMapper配置

 5、创建测试类

二、注解绑定

步骤

1、创建pojo类(Teacher 对象)

2、创建TeacherMapper接口

 3、更改配置

 4、创建测试类TeacherMapperTest


mybatis实现了接口绑定,使用会更加方便

接口绑定:mybatis中任意定义接口,然后把接口里面的方法和SQL语句绑定,就可以直接调用接口方法就可以

接口绑定方式

通过注解绑定,直接在方法上面加上@Select @Update等注解,在注解里包含SQL绑定

通过XML里面SQL绑定,需要在xml配置文件里的namespace必须指定接口的全限定名

一、配置xml文件

步骤

1、创建pojo类(自定义对象类)

2、创建mapper.java接口

3、创建mapper.xml配置文件

4、在mymybatis-config.xml中添加mapper配置

5、创建测试类

 这里以student表为例进行编码:

1、创建pojo类(Student对象)

给定是四个属性 SID,Sname,Ssex,Sage

并 右击 generate 出他们的getter and setter 和 toString()方法

public class Student {
    private Integer SID;
    private String Sname;
    private String Ssex;
    private Integer Sage;

    public Integer getSID() {
        return SID;
    }

    public void setSID(Integer SID) {
        this.SID = SID;
    }

    public String getSname() {
        return Sname;
    }

    public void setSname(String sname) {
        Sname = sname;
    }

    public String getSsex() {
        return Ssex;
    }

    public void setSsex(String ssex) {
        Ssex = ssex;
    }

    public Integer getSage() {
        return Sage;
    }

    public void setSage(Integer sage) {
        Sage = sage;
    }

    @Override
    public String toString() {
        return "Student{" +
                "SID=" + SID +
                ", Sname='" + Sname + '\'' +
                ", Ssex='" + Ssex + '\'' +
                ", Sage=" + Sage +
                '}';
    }
}

 2、创建StudentMapper接口

import com.tulun.pojo.Student;


import java.util.List;

public interface StudentMapper {

    //通过id来查询某一个学生信息
//    @Select("select * from cheche where SID = #{id}")
    public Student selectStudentById(Integer id);
//   通过id删除某条学生数据
    public void  deleteStudentById(Integer id);
    //查询所有数据
    public List selectAllStudent();
//动态查询数据
    public List selectStudent(Student student);

}

 3、创建mapper.xml配置文件







    
    

    
        delete from cheche where SID = #{id}
    


    
  
    

 4、在mybatis-config.xml中添加StudentMapper配置

  
        

    

 5、创建测试类


import com.tulun.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;


public class StudentMapperTest {
    SqlSessionFactory sqlSessionFactory = null;
    @Before
public void before(){
        String resource = "mybatis-config.xml";
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        System.out.println("before方法执行结束");
    }

    @Test
    public void selectStudentById() {
        System.out.println("查询数据的方法开始执行");


        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //第一种 原始直接调用方法
//        Student o = sqlSession.selectOne("com.tulun.mapper.StudentMapper.selectStudentById",2);
//        System.out.println(o);

        //第二种方法 代理模式  代理对象需要依赖于原始调用方法

        //通过接口获取对象实例
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

        //测试接口
        Student student = studentMapper.selectStudentById(2);
            System.out.println(student);

    }


    @Test
    public void selectAllStudent() {
        System.out.println("查询数据的方法开始执行");
        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();


        //原始调用方式
//        List student = sqlSession.selectList("com.tulun.mapper.StudentMapper.selectAllStudent");
//        Iterator iterator1 = student.iterator();
//        while (iterator1.hasNext()){
//            System.out.println(iterator1.next());
//        }
//        System.out.println("-------------------------------");


        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List selectAllStudent = mapper.selectAllStudent();
        Iterator iterator = selectAllStudent.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    @Test
    public void deleteStudentById() {
        System.out.println("删除方法开始执行");

        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过接口获取对象实例
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.deleteStudentById(2);
        sqlSession.commit();
    }


    @Test
    public void  selectStudent(){

        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setSID(1);
        student.setSname("88");
//        List students = studentMapper.selectStudent(student);
//
//        Iterator iterator = students.iterator();
//        while (iterator.hasNext()){
//            System.out.println(iterator.next());
//        }


    }

    @After
    public void  after() {
        System.out.println("after方法执行结束");
    }

}

二、注解绑定

步骤

1、创建pojo类

2、创建mapper.java接口

3、在mybatis-config.xml中添加mapper配置

4、创建测试类

这里以teacher表为例进行编码:

1、创建pojo类(Teacher 对象)

给定是三个属性 id,name,sex

并 右击 generate 出他们的getter and setter 和 toString()方法

public class Teacher {
    private Integer id;
    private String name;
    private String sex;

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

2、创建TeacherMapper接口

里面给定要操作数据库的方法 

在方法的上方写上sql语句

格式为: @Insert("sql语句") 

import org.apache.ibatis.annotations.*;
import com.tulun.pojo.Teacher;

import java.util.List;

interface TeacherMapper {
    //注解形式
//    @Results(id="teacherResult",value = {
//            @Result(property = "id",column = "id",id =true),
//            @Result(property = "s",column = "sex")}
//            )
    //选择
    @Select("select * from teacher where id = #{id}")
    public Teacher selectTeacherById(Integer id);

    //删除
    @Delete("delect from teacher where id = #{id}")
    public void  deleteTeacherById(Integer id);


    //添加
   // @Options(useGeneratedKeys = true ,keyColumn = "id")
    @Insert("insert into teacher(id,name,sex) values (#{id},#{name},#{sex})")
    public int insertTeacherById(Teacher teacher);

}

 3、更改配置

将mybatis-config.xml中的mapper标签里的内容更改

    
        

        
    

 4、创建测试类TeacherMapperTest

import com.tulun.pojo.Teacher;
import org.apache.ibatis.io.Resources;
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.IOException;
import java.io.InputStream;

import static org.junit.Assert.*;

public class TeacherMapperTest {
    SqlSessionFactory sqlSessionFactory = null;
    @Before
    public void before(){
        String resource = "mybatis-config.xml";
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        System.out.println("before方法执行结束");
    }

    @Test
    public void selectTeacherById() {

    }

    @Test
    public void deleteTeacherById() {
    }

    @Test
    public void updateTeacherById() {
    }

    @Test
    public void insertTeacherById() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = new Teacher();
        teacher.setId(10);
        teacher.setName("jing");
        teacher.setSex("nv");
        teacherMapper.insertTeacherById(teacher);
        sqlSession.commit();
    }
}

这里主要演示一下 插入操作(其余操作类似)

插入一组数据(id是10,name是jing,sex 是nv)

执行操作之前数据库里的内容:

mybatis的接口绑定方式(注解绑定和配置xml文件)_第1张图片

执行插入操作之后数据库内容为:

mybatis的接口绑定方式(注解绑定和配置xml文件)_第2张图片

插入成功!

这里还有一个知识点关于属性值自增问题

@Options(useGeneratedKeys = true ,keyColumn = "id")
在sql语句的上方将自增的属性值打开,并指定id是哪个自增属性。

假如id可以自增,那在TeacherMapperTest类中传参数时不需要传入id值,在数据库中会根据id字段中最大的数据接着自增。

   @Options(useGeneratedKeys = true ,keyColumn = "id")
    @Insert("insert into teacher(id,name,sex) values (#{id},#{name},#{sex})")
    public int insertTeacherById(Teacher teacher);

 再次运行插入结果如下:

mybatis的接口绑定方式(注解绑定和配置xml文件)_第3张图片

在java代码中打开自增的按钮,还需要你的数据库中该属性可以有主键和自增的约束,在我的数据库中,teacher表中的id属性约束是:

mybatis的接口绑定方式(注解绑定和配置xml文件)_第4张图片

 @select操作

当java中teacher对象中的属性和数据库中的属性名完全一致时,会自动识别映射

mybatis的接口绑定方式(注解绑定和配置xml文件)_第5张图片

 但当java中属性sex变成s时,和数据库中的sex不匹配,想要把他俩匹配起来,要怎样做呢?

mybatis的接口绑定方式(注解绑定和配置xml文件)_第6张图片

在TeacherMapper.java中添加如下代码,这样可以将java中的属性和数据库中的属性进行匹配 

@Results(id="teacherResult",value = {
            @Result(property = "id",column = "id",id =true),
            @Result(property = "s",column = "sex")}
            )
    @Select("select * from teacher where id = #{id}")
    public Teacher selectTeacherById(Integer id);

 mybatis的接口绑定方式(注解绑定和配置xml文件)_第7张图片

@select 

查询表中的所有数据

StudentMapper.java 类中的方法

   public List selectAllStudent();

StudentMapperTest.java类中selectALLStudent方法:

SqlSessionFactory sqlSessionFactory = null;
    @Before
public void before(){
        String resource = "mybatis-config.xml";
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        System.out.println("before方法执行结束");
    }
 @Test
    public void selectAllStudent() {
        System.out.println("查询数据的方法开始执行");
        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List selectAllStudent = mapper.selectAllStudent();
        //把获取的Student对象一一打印出来
        Iterator iterator = selectAllStudent.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

执行结果: 

mybatis的接口绑定方式(注解绑定和配置xml文件)_第8张图片

 添加原始调用方式来进行比较,可以得到同样的结果。

SqlSessionFactory sqlSessionFactory = null;
    @Before
public void before(){
        String resource = "mybatis-config.xml";
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        System.out.println("before方法执行结束");
    }
 @Test
    public void selectAllStudent() {
        System.out.println("查询数据的方法开始执行");


        //获取会话
        SqlSession sqlSession = sqlSessionFactory.openSession();



        //原始调用方式
        List student = sqlSession.selectList("com.tulun.mapper.StudentMapper.selectAllStudent");
        Iterator iterator1 = student.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
        System.out.println("-------------------------------");

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List selectAllStudent = mapper.selectAllStudent();
        //把获取的Student对象一一打印出来
        Iterator iterator = selectAllStudent.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

mybatis的接口绑定方式(注解绑定和配置xml文件)_第9张图片

你可能感兴趣的:(框架学习,mybatis,java,xml,接口,1024程序员节)