MyBatis [developed using annotations]

8. Development using annotations

8.1 Interface-oriented development

three facets of difference

Object-oriented means that when we consider a problem, we take the object as a unit and consider its properties and methods;

Process-oriented means that when we consider a problem, we take a specific process (business process) as a unit and consider its realization;

Interface design and non-interface design are for reuse technology, and object-oriented (process) is not a problem, but more reflected in the overall architecture of the system;

8.2 Development using annotations

1. Annotations are implemented on interfaces

   @Select("select * from mybatis.user")
    List<User> getUsers();

2. Binding in the core configuration file

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

3. Test

public class UserMapperTest {

    @Test
    public void test(){
        SqlSession sqlSesssion = MybatisUtils.getSqlSesssion();
        //底层主要应用反射
        UserMapper mapper = sqlSesssion.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user: users
             ) {
            System.out.println(user);
        }
        sqlSesssion.close();
    }

Essence: reflection mechanism implementation

Bottom layer: dynamic proxy

Mybatis detailed execution process

 8.3 CRUD

We can automatically commit transactions when the tool class is created

 @Test
    public void test(){
        SqlSession sqlSesssion = MybatisUtils.getSqlSesssion();
        //底层主要应用反射
        UserMapper mapper = sqlSesssion.getMapper(UserMapper.class);
       /* User user = mapper.getUserById(1);
        System.out.println(user);*/
        /*for (User user: users
             ) {
            System.out.println(user);
        }*/
        mapper.addUser(new User(5,"youyou","123123"));

        sqlSesssion.close();
    }
 @Select("select * from mybatis.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},#{password})")
    int addUser(User user);
<!--绑定接口-->
    <mappers>
        <mapper class="com.jiang.mapper.UserMapper"></mapper>
    </mappers>

About @Param() annotation

  • Parameters of basic type or String type need to be added
  • Reference types do not need to add
  • If there is only one basic type, it can be ignored, but it is recommended that everyone add it
  • What we refer to in SQL is the attribute name set in our @Param() here

#{} and ${}

#There is pre-compiled meaning to prevent SQL injection


https://www.bilibili.com/video/BV1NE411Q7Nx?p=19&spm_id_from=pageDriver

Guess you like

Origin blog.csdn.net/qq_48108092/article/details/124168650