2.MyBatis的增删查改


1.创建数据库
2.数据库连接测试
3.导入依赖:mysql、mybatis、junit
4.编写mybatis-config.xml核心配置文件
5.编写Utils工具类
6.编写实体类
7.编写Mapper
8.Mapper文件注册
9.资源过滤
10.测试
11.map传参
12.模糊查询
13.${}和#{}的区别

1.创建数据库

2.数据库连接测试

3.导入依赖:mysql、mybatis、junit

依赖代码

    
        
        
            mysql
            mysql-connector-java
            5.1.47
        
        
        
            org.mybatis
            mybatis
            3.5.2
        
        
        
            junit
            junit
            4.13.1
            test
        
    

4.编写mybatis-config.xml核心配置文件

Mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8"?>





   
    
    
        
            
            
                
                
                
                
            
        
    

5.编写Utils工具类

1.通过Mybatis的Resources工具类将MyBatis核心配置文件转为流,再通过局部对象SqlSessionFactoryBuilder使用build方法将MyBatis核心对象SqlSessionFactory得到,SqlSessionFactoryBuilder使用了mybatis-config.xml的配置参数得到了单例SqlSession后将mybatis-config.xml释放。

点击查看代码
package com.user102;

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 java.io.InputStream;

public class Utils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resources="mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

6.编写实体类

点击查看代码
package com.user102.pojo;

public class Student {
    private String sno;
    private String sname;
    private int age;
    private String sex;
    private String address;

    public Student(String sno, String sname, int age, String sex, String address) {
        this.sno = sno;
        this.sname = sname;
        this.age = age;
        this.sex = sex;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sno='" + sno + '\'' +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}'+"\n";
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

7.编写Mapper

Mapper接口
public interface StudentMapper {
    public int addStudent(Student student);
    public int subStudent(String sno);
    public int updateStudent(Student student);
    public Student getStudentForSno(String sno);
}

XML文件代码

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



    
        insert into mybatis.student values('${sno}','${sname}',${age},'${sex}','${address}')
    
    
        delete from mybatis.student where sno='${sno}'
    
    
        update mybatis.student set sno='${sno}',sname='${sname}',age=${age},sex='${sex}',address='${address}'
        where sno='${sno}'
    
    

XML文件代码其实就是接口的实现类。

8.Mapper文件注册

在dao层有一个接口,还有一个XML配置文件(接口的实现);将XML进行注册时,便能让SqlSession找到Mapper(SqlSession通过类名得到Mapper),XML通过指定命名空间namespace表明了实例化哪个接口

若不将XML文件进行注册,sqlSession.getMapper(XXX.class)时,便找不到Mapper。

点击查看代码
    
        
    

9.资源过滤

不进行资源过滤,非resource文件夹的文件将不会视为资源文件

资源过滤
    
        
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                
                false
            
            
                src/main/resources
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
    

10.测试

①增加


增加测试代码
    public void addStudent(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.addStudent(new Student("160121454125","愚公公",60,"男","太行山"));
        sqlSession.commit();
        sqlSession.close();
    }

②删除


删除测试代码
    public void subStudent(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.subStudent("160121454124");
        sqlSession.commit();
        sqlSession.close();
    }

③改


修改测试代码
    public void updateStudent(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.updateStudent(new Student("160121454125","姜太公",80,"男","湖中亭"));
        sqlSession.commit();
        sqlSession.close();
    }

④查

查询测试代码
    public void getStudentForId(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student studentForSno = mapper.getStudentForSno("160121454125");
        System.out.println(studentForSno);
        sqlSession.commit();
        sqlSession.close();
    }

文件目录

11.map传参
当一个对象有很多属性时,只使用其中某几个属性,可以使用map传参,也是工作中常用的方法

删除sname为“愚公公”,address为“太行山”的所有数据

编写Mapper接口及XML文件

点击查看代码
    public int deleteStudent(Map map);

点击查看代码
    
        delete from mybatis.student where sname='${mySname}' and address='${myAddress}'
    

测试

点击查看代码
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        HashMap  map = new HashMap ();
        map.put("mySname","愚公公");
        map.put("myAddress","太行山");
        mapper.deleteStudent(map);
        sqlSession.commit();
        sqlSession.close();

12.模糊查询


查询包含李的所有学生数据

编写Mapper接口及XML文件
第一种方式:

点击查看代码
public List  likeThisName1(String name);

点击查看代码
    

测试

点击查看代码
    public void likeThisName1(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List  students = mapper.likeThisName1("%李%");
        System.out.println(students);
        sqlSession.close();
    }

第二种方式:

点击查看代码
public List  likeThisName2(String name);

点击查看代码
    

测试:

拼接出的SQL代码出错

解决方法:将${}改为#{}:

success:

点击查看代码
    public void likeThisName2(){
        SqlSession sqlSession = Utils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List  students = mapper.likeThisName2("李");
        System.out.println(students);
        sqlSession.close();
    }

13.${}和#{}的区别

#{}和${}这两个语法是为了动态传递参数而存在的,是Mybatis实现动态SQL的基础,总体上他们的作用是一致的(为了动态传参),但是在编译过程、是否自动加单引号、安全性、使用场景等方面有很多不同,下面详细比较两者间的区别:

  • 1.编译过程:
    #{} 是 占位符 :动态解析 -> 预编译 -> 执行
    ${} 是 拼接符 :动态解析 -> 编译 -> 执行

  • 2.自动加单引号:
    #{} 对应的变量会自动加上单引号
    ${} 对应的变量不会加上单引号

  • 3.安全性:
    #{} 能防止sql 注入
    ${} 不能防止sql 注入

建议以后使用#{}进行动态传参,更加安全和高效