Mybatis annotation development

Mybatis

8. Using annotation development

8.1 interface oriented programming

  • Everyone has studied object-oriented programming and interface before, but in real development, we often choose interface oriented programming.
  • Root cause: decouple, expand and improve reuse. In layered development, the upper layer does not care about the specific implementation. Everyone abides by common standards, making the development easier and more standardized.
  • In an object-oriented system, various functions of the system are completed by many different objects. In this case, how each object implements itself is not so important for system designers.
  • The cooperative relationship between various objects has become the key of system design. From the communication between different classes to the interaction between modules, we should focus on it at the beginning of system design, which is also the main work of system design. Interface oriented programming means programming according to this idea.

8.2 understanding of interface

  • From a deeper understanding, the interface should be the separation of definition (specification, constraint) and Implementation (the principle of separation of name and reality).

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

  • There shall be two types of interfaces:

    • The first type is the abstraction of an individual, which can correspond to an abstract class.
    • The second is the abstraction of an aspect of an individual, that is, the formation of an abstract interface.
  • An individual may have multiple Abstract faces. Abstract body and abstract surface are different.

8.3. Three oriented differences

  • Object oriented means that when we consider a problem, we take the object as the unit and consider its attributes and methods.
  • Process oriented means that when we consider a problem, we consider its implementation in a specific process (transaction process).
  • Interface design and non interface design are aimed at reuse technology, and object-oriented (process) is not a problem. It is more reflected in the overall architecture of the system

8.4 annotation development

  • Annotations are implemented on the interface.

    •  @Select("select * from user")
          List<User> getUsers();
      
  • You need to bind the interface in the core configuration file!

    •   <mapper class="com.jcooling.mapper.UserMapper"></mapper>
      
  • test

    •  @Test
          public void testGetUsers(){
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              List<User> users = mapper.getUsers();
              for (User user : users) {
                  System.out.println(user);
              }
      
  • Essence: reflection mechanism implementation.

  • Bottom layer: dynamic proxy.




























































































8.5 execution process of Mybatis

  • Resources gets and loads the global configuration file.
  • Instantiate the SqlSessionFactoryBuilder constructor.
  • Parse the configuration file stream XMLConfigBuilder.
  • Configuration all configuration information.
  • SqlSessionFactory instantiation.
  • transactional transaction management.
  • Create executor executor.
  • Create sqlSession.
  • Implement CRUD.
  • Check whether the execution is successful.
  • Submit things. (rollback)
  • close.

8.6,CRUD

  • We can automatically commit transactions when the tool class is created! (not recommended)

    •  public static SqlSession getSqlSession(){
              return sqlSessionFactory.openSession(true);
          }
      
  • Write the interface and add comments.

    • public interface UserMapper {
          @Select("select * from user")
          List<User> getUsers();
      
          //Method has multiple parameters. All parameters must be preceded by @ Param ("id") annotation
          @Select("select * from user where id=#{id} and name=#{name}")
          User getUserById(@Param("id") Integer id,@Param("name") String name);
      
          @Insert("insert into user 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=#{id}")
          int deleteUser(int id);
      }
      
    • Test class

      • Note: we must bind the interface registration to our core configuration file!

      • public class UserMapperTest {
            @Test
            public void testGetUsers(){
                SqlSession sqlSession = MybatisUtils.getSqlSession();
                //The bottom layer mainly applies reflection
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                List<User> users = mapper.getUsers();
                for (User user : users) {
                    System.out.println(user);
                }
                sqlSession.close();
            }
        
            @Test
            public void testGetUserById(){
                SqlSession sqlSession = MybatisUtils.getSqlSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                User userById = mapper.getUserById(4,"4");
                System.out.println(userById);
                sqlSession.close();
            }
        
            @Test
            public void testAddUser(){
                SqlSession sqlSession = MybatisUtils.getSqlSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                int i = mapper.addUser(new User(7, "6", "6"));
                if (i!= 1) {
                    System.out.println("Insert failed");
                }else {
                    System.out.println("Insert successful");
                }
                sqlSession.commit();
                sqlSession.close();
            }
        
            @Test
            public void testUpdateUser(){
                SqlSession sqlSession = MybatisUtils.getSqlSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                int i = mapper.updateUser(new User(7, "5", "6"));
                if (i!= 1) {
                    System.out.println("Update failed");
                }else {
                    System.out.println("Update succeeded");
                }
                sqlSession.commit();
                sqlSession.close();
            }
        
            @Test
            public void testDeleteUser(){
                SqlSession sqlSession = MybatisUtils.getSqlSession();
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                int i = mapper.deleteUser(6);
                if (i!= 1) {
                    System.out.println("Deletion failed");
                }else {
                    System.out.println("Delete succeeded");
                }
                sqlSession.commit();
                sqlSession.close();
            }
        }
        
  • About @ Param() annotation

    • Parameters of basic type or String type need to be added.

    • Reference types do not need to be added.

    • If there is only one basic type, it can be ignored. (recommended to add)

    • What we refer to in SQL is the property name set in @ Param().

  • About #{} and ${}

    • #{}:

      • It is used to pass in parameters. When parsing, sql will add "", which will be parsed as a string.
      • #It can prevent sq injection to a great extent.
    • ${}

      • The data passed in with ${} is directly displayed in the generated sql.
      • The ${} method cannot prevent sql injection.
      • ${} is generally used to enter the incoming database objects, such as database table names.
      • Try to use #{} when you can

Posted on Sun, 28 Nov 2021 15:54:45 -0500 by ATLien