1.面向接口编程

  • 使用面向接口编程的根本原因:解耦,可拓展,提高复用。

  • 分层开发中,上层不用管具体的实现,大家都遵循共同的标准,使得开发变得更容易,规范性更好。


2.注解的基本步骤

  1. 编写基本的配置文件【mybatis-config.xml】

  2. 编写pojo类

  3. 编写Dao层接口

    //org.example.dao.UserMapper
    public interface UserMapper {
        @Select("select * from user")
        List<User> getUser();
    }
    

4.在配置文件【mybatis-config.xml】中注册Mappers,绑定接口

    <mappers>
        <mapper class="org.example.dao.UserMapper"/>
    </mappers>

5.测试

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList=mapper.getUser();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

3.本质

Java反射机制的实现

4.基于注解的增删改查

4.1自动提交

之前写的工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try{
            //获取 SqlSessionFactory 对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    //获取sqlSession实例
    public static SqlSession getSqlSession(){
         //true表示自动提交
         return sqlSessionFactory.openSession(true);
    }
}

4.2 当parameterType 有多个参数

使用注解的方法----------@Param

User getUserById(@Param("id") int id,@Param("name") String name);

无论是采用注解进行增删改查还是用xml, 其他的照常写

注意! 在写sql语句提取参数的时候,要写@Param里的参数名字

4.3 增删改查

  • @Select("sql语句") 查

  • @Insert("sql语句") 增

  • @Delete("sql语句") 删

  • @Update("sql语句") 改