Mybatis原生操作

22 阅读1分钟

原生操作

Mybatis --> 数据库连接池 --> 驱动 --> 数据库

SqlSessionFactory --> SqlSession --> SqlSession增删改查

public class MyBatisUtil {
    private static SqlSessionFactory factory = null;

    static {
        try {
            String config = "mybatis-config.xml";
            InputStream in = Resources.getResourceAsStream(config);
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            factory = null;
            e.printStackTrace();
        }
    }

    /* 获取SqlSession对象 */
    public static SqlSession getSqlSession() {
        SqlSession session = null;
        if (factory != null) {
            session = factory.openSession();
        }
        return session;
    }
} 
public void testUtils() throws IOException {
    SqlSession session = MyBatisUtil.getSqlSession();
    List<Student> studentList = session.selectList(
        "cn.ccb.dao.StudentDao.selectStudents");
    studentList.forEach(student -> System.out.println(student));
    session.close();
}

方法不能重载

因为是全限名+方法名的寻找策略 当调用接口方法时,接口全限名+方法名,拼接字符串作为 key 值,从而定位到MappedStatement ,举 例: com.mybatis3.mappers.StudentDao.findStudentById,可以唯⼀找到Xml中namespace 为 com.mybatis3.mappers.StudentDao中的id = findStudentById 的MappedStatement

如何实现sql执行结果和目标对象映射的

  • 第⼀种是使⽤ <resultMap> 标签,逐⼀定义列名和对象属性名之间的映射关系

  • 第⼆种是使用sql 列的别名功能,比如 T_NAME as name

#{} 和 ${} 区别

  • #{}是预编译处理、是占位符, ${}是字符串替换、是拼接符
  • #{}添加参数时值的两边有‘’${}添加参数时值两边没有'',有sql注入风险

${}导致sql注入的情况

select * from user where account = 122221122 and password = 12252152521 or 1=1

#{}防止sql注入的情况

select * from user where account = 122221122 and password = '12252152521 or 1=1'