Mybatis学习笔记


Mybati使用笔记

创建一个maven项目

导入依赖

依赖查询地址:https://mvnrepository.com/artifact/org.mybatis/mybatis

Mybatis中网官方文档:https://mybatis.net.cn/getting-started.html

		
        
            mysql
            mysql-connector-java
            5.1.47
        

        
        
        
            org.mybatis
            mybatis
            3.5.2
        

        
        
            junit
            junit
            4.12
        

编写Mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>





    
     

    
        
        
        
    

    
        
    


    
    
        
    


    

        
            

            
                
                
                
                
                
                
            
        

    

    
    

        


        
        
        

    


jdbc.properties配置文件

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=5
jdbc.maxActive=10

编写Mybatis工具

从 XML 中构建 SqlSessionFactory

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
为了方便,编写工具类获取SqlSession
//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            //使用Mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
    public static SqlSession  getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

编写代码

创建实体类

ublic class Student {
    //定义属性名 目前要求是属性名和列明一样
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student() {
    }

    public Student(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

编写mapper接口

//接口操作student表
public interface StudentDao {

    //查询student表的所有数据
    public List selectStudents();

    //插入操作
    public int insertStudent(Student student);


    /*
     * 参数的使用
     *   1、一个简单的参数*/
    public Student selectStudentById(Integer id);

    /*  2、多个参数,在形参定义面前加入 @Param("自定义参数名称")*/
    public List listStudent(@Param("myname") String name, @Param("myage") int age);

    /*  2、多个参数,另一种方式传递参数*/
    public List listStudent22(String name, int age);


    public Student resultmap(Integer id);
}

编写mapper.xml配置

<?xml version="1.0" encoding="UTF-8" ?>





    
    
    
    
	
    
    
    
    
        insert into student values(#{id},#{name},#{email},#{age})
    
    
    

    
    
    
    
        
           
        
        
        
    
    
    


测试

@Test  //查询测试
public void test3() {
    //获得SqlSession对象
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    //执行sql 
    StudentDao dao = sqlSession.getMapper(StudentDao.class);
    //调用方法
    System.out.println(dao.selectStudentById(1001));
    //关闭SqlSession
    sqlSession.close();

}


@Test  //插入测试
public void test3() {
    //获得SqlSession对象
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    //执行sql 
    StudentDao dao = sqlSession.getMapper(StudentDao.class);
    //调用方法
    dao.insertStudent(new Student(1,"name","123@qq.com",18));
    //提交事务    -----------所有的 增删改 都需要提交事务
    sqlSession.commit();
    //关闭SqlSession
    sqlSession.close();

}

注意点
  • 每一个mapper配置文件都需要在mapper核心配置文件注册
  • 资源过滤问题
    
        
            
                src/main/java/
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
    


  • 绑定接口错误
  • 方法名不对
  • 返回类型不对
  • 所有的增删改都需要提交事务

以上只是简单介绍,参考狂神视频:https://www.bilibili.com/video/BV1NE411Q7Nx?p=9&spm_id_from=pageDriver

后面自行查看文档,培养看文档写代码的能力