[6] Mybatis uses annotations, Lombok plug-in use

8. Use annotation development

8.1, interface-oriented programming

  • I have learned object-oriented programming and interfaces before, but in real development, many times we will choose interface-oriented programming
  • The root cause: decoupling, extensibility, improved reuse, layered development, the upper layer does not care about the specific implementation, everyone abides by the common standard, which makes development easier and better standardized
  • In an object-oriented system, the various functions of the system are completed by the cooperation of many different objects. In this case, how each object implements itself is not so important to the system designer;
  • The collaborative relationship between various objects has become the key to system design. From the communication between different types to the interaction between the modules, it is important to consider at the beginning of system design, which is also the main work content of system design. Interface-oriented programming refers to programming in accordance with this idea.

Understanding of the interface

  • From a deeper understanding of the interface, it should be the separation of definition (standards, constraints) and implementation (the principle of separation of name and reality).

  • The interface itself reflects the system designer's abstract understanding of the system.

  • There should be two types of interfaces:

    • The first category is the abstraction of an individual, which can correspond to an abstract class;
    • The second category is the abstraction of a certain aspect of an individual, that is, forming an abstract surface (interface);
  • A body may have multiple abstract faces. There is a difference between abstract body and abstract surface.

Three aspects of difference

  • Object-oriented means that when we consider the problem, we take the object as the unit and consider its properties and methods.
  • Process-oriented means that when we consider a problem, we take a specific process (transaction 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. The more manifestation is the overall architecture of the system

8.2. Development using annotations

  1. Annotations are implemented on the interface

  2. Need to bind the interface in the mybatis-config.xml file

        <!--每一个mapper.xml都需要在mybatis核心配置文件中进行注册,进行映射-->
        <mappers>
            <mapper resource="com/kuber/dao/UserMapper.xml"/>
        </mappers>
    
  3. Test use

        @Test
        public void getAllUser(){
          
          
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //底层主要应用反射
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getAllUser();
            for (User user : users) {
          
          
                System.out.println(user);
            }
            sqlSession.close();
        }
    
  4. Use Debug to view the essence

    Insert picture description here

  5. Essentially uses the dynamic proxy mechanism of jvm

    Insert picture description here

  6. Mybatis detailed execution process

    Insert picture description here

Essence: Implementation of reflection mechanism

Bottom layer: dynamic proxy

8.3. Annotation to realize CRUD

The transaction can be automatically committed when the tool class is created, as follows

    public static SqlSession getSqlSession(){
    
    
        return sqlSessionFactory.openSession(true);
    }

Insert picture description here

Inquire

Can be implemented in the interface method

    @Select("select * from users where uid = #{uid}")
    User getUserByID(@Param("uid") int id);

The test category is no longer displayed

insert

    @Insert("insert into users values(null,#{username},#{password})")
    int addUser(User user);

delete

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

modify

    @Update("update users set username = #{username},password = #{password} where uid = #{uid}")
    int updateUser(User user);

8.4. About @Param

The @Param annotation is used to give a name to the method parameter. The following is a summary of the principles of use:

  • When the method only accepts one parameter, @Param can be omitted.
  • When the method accepts multiple parameters, it is recommended to use the @Param annotation to name the parameters.
  • If the parameter is a JavaBean, @Param cannot be used.
  • When the @Param annotation is not used, there can only be one parameter, and it is a Javabean.

8.5, the difference between # and $

  • The function of #{} is mainly to replace the placeholders in the PrepareStatement? [Recommended use]

    INSERT INTO user (name) VALUES (#{name});
    INSERT INTO user (name) VALUES (?);
    
  • The function of ${} is to directly replace strings

    INSERT INTO user (name) VALUES ('${name}');
    INSERT INTO user (name) VALUES ('kuangshen');
    

9 、 Lombok

Steps for usage:

  1. Install the lombok plugin in idea (restart idea)

  2. Import the jar package in lombok into the project (maven goes directly to the maven warehouse to find the coordinates)

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
                <scope>provided</scope>
            </dependency>
    
  3. Annotate the entity class

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/109565142