1、根据xml配置创建一个sqlsessionfactory的对象
 有数据源的一些运行环境信息
 2、sql映射文件,配置了每一个sql,以及sql的封装规则
 3、将sql注册在全局配置文件中
4、coding
 1)根据全局配置文件得到SqlsessionFactory
 2)试用sqlsession工厂,获取到sqlsession对象试用它来执行增删改查
 一个sqlsession就是代表与数据库的一次对话,用完关闭(close)
 3)使用sql唯一标识该告诉mybatis执行哪个sql,sql都是保存在sql映射文件中

 

Mybatis学习记录

 

Mybatis学习记录

 

 

String resource = "mybatis-config.xml";

InputStream inputStrem = Resource.getResoureceAsStream(resource);

SqlsessionFactory sessionFactory = new SqlSessionFactoryBuilder().Builder(resource);//获取sqlsessionfactory对象

 SqlSession opensession = sessionFactory.openSession();//使用opensession方法获取sqlsession对象

 

加载数据库信息-->创建sqlsession工厂-->用OpenSession()方法创建sqlsession,每个sqlsession都是一个数据库查询实例

//获取接口的实现类对象
//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法


EmployeeMapper mapper = opensession.getMapper(EmployeeMapper.class);//获取接口的实现类对象
Employee empById = mapper.getEmpById(1);//调用接口的方法
System.out.println(mapper.getClass());
System.out.println(empById);

 

 传多个参数时候需要加上@Param(“xx”)。

用注解来简化xml配置的时候,@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中 

 Mybatis学习记录

Mybatis学习记录

 jdbc oracle

Mybatis学习记录

 

 mybatis 在接口类中传参

Mybatis学习记录

 

 

#{}和${}的区别:

个人理解就是#{}防止sql注入 

${}用于处理sql语句中动态填入的部分,例如某个图书的info表 书名_info_tbl,这时候书名就该直接拼接进来。又如下图样例中年份工资表和排序规则。没法sql预编译,只能拼接。

Mybatis学习记录

 Mybatis学习记录

 

有时候resultType返回可能为null时,自己写个resultMap

例如DepartmentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.dao.DepartmentMapper">
    <resultMap type="com.atguigu.mybatis.bean.Department" >
        <id column="dept_id" property="id"/>
        <result column="dept_name" property="department_name"/>
    </resultMap>
    <select >
        select id,dept_name from tbl_department where id = #{id}
    </select>
</mapper>
View Code

相关文章:

  • 2021-07-29
  • 2021-10-13
  • 2021-12-12
  • 2021-10-12
  • 2021-08-20
  • 2021-12-27
  • 2021-06-03
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-11-26
  • 2021-10-20
  • 2022-12-23
  • 2021-04-24
相关资源
相似解决方案