MyBatis(5)——注解和Mybatis详细的执行流程

1.1 面向接口编程

根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好。

接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离

接口的本身反映了系统设计人员对系统的抽象理解。

1.2 利用注解开发

在这里插入图片描述

注意:利用注解开发就不需要mapper.xml映射文件了

1、我们在我们的接口中添加注解

    //根据查询全部用户
    @Select("select * from user")
    List<User> getUsers();

2、在mybatis的核心配置文件中注入

<!--    绑定接口-->
    <mappers>
        <mapper class="com.xxxx.dao.UserMapper"/>
    </mappers>

3、我们去进行测试

 @Test
   public  void test(){
    
    
       try(SqlSession sqlSession = MyBatisUtils.getSqlSesion();){
    
    
           UserMapper mapper = sqlSession.getMapper(UserMapper.class);
           List<User> users = mapper.getUsers();
           for (User user:users
                ) {
    
    
               System.out.println(user);
           }
       }
   }

自动提交事务
在这里插入图片描述

    public static SqlSession getSqlSesion() {
    
    
//        自动提交事务
        return sqlSessionFactory.openSession(true);
    }

interface接口
在这里插入图片描述

public interface UserMapper {
    
    
    //根据查询全部用户
    @Select("select * from user")
    List<User> getUsers();

//    方法存在多个参数,所有的参数前面必须加上@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id );

    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
    int addUser(User user);

    @Update("update user set name = #{name} , pwd = #{pwd} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
}

一定要注意:j将接口注册绑定到我们的核心配置文件中

<!--    绑定接口-->
    <mappers>
        <mapper class="com.xxxx.dao.UserMapper"/>
    </mappers>

方法存在多个参数,所有的参数前面必须加上@Param
1 无论基本类型的或者String需要加上
2 引用类型不需要加
3 如果只有一个基本类型可以忽略,但是建议大家加上。
4 sql中引用的就是这里的@param里面的参数

1.3 Mybatis详细的执行流程

在这里插入图片描述

在这里插入图片描述
1 Resources加载全局配置文件

 **String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);**

2 实例化SqlSessionFactoryBuilder对象

**sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);**

3 XMLConfigBuilder 解析配置文件流

**build**
  **XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);**

4 把解析的配置信息放入Configuration 实例化DefaultSqlSessionFactory

 public SqlSessionFactory build(Configuration config) {
    
    
    return new DefaultSqlSessionFactory(config);
  }

。。。。

猜你喜欢

转载自blog.csdn.net/zs18753479279/article/details/110825195