mybatis04 -- developing with annotations

1 review - Interface oriented programming

Root cause: decoupling, expandable, improved 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. The cooperative relationship between various objects has become the key of system design.

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.

    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

2 development using annotations

Mapper is not required for annotation development xml Mapping file (there are limitations to this approach, and xml file mapping is still required for complexity)

According to the original practice, the method written here should be in mapper XML. Then bind mappers in the core configuration file

No need now. Write sql statements in parentheses with annotations on it, and then go to the core configuration file to bind the interface. mappers is still used. mappers can be bound in several ways, but in the interface mode.

So mapper XML can be removed, and its mappers in the core configuration file should also be rebound.

step

  1. Add annotations to the interface

    public interface UserMapper {
        @Select("select id,mname,pwd password from mybatis.user")
         List<User> getUsers();
    
    }
    
  2. Bind mappers in the core configuration file and use the interface

    <mappers>
        <mapper class="com.kuang.dao.UserMapper"/>
    </mappers>
    
  3. test

    In essence, reflection is adopted to obtain the class usermapper Class, you can get the information inside

    Bottom layer: dynamic proxy mechanism of jvm

    [the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-karqwjcb-1620701125627) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210510211651671. PNG)]

    @Test
    public void getUsers(){
        SqlSession sqlsession = MybatisUtils.getSqlsession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        List<User> userList = mapper. getUsers();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlsession.close();
    }
    

Detailed execution process of 3Mybatis

The underlying build of SqlSessionFactoryBuilder is to parse the configuration file information. The XMLConfiguration object is new ly created in the build. The parameters are inputstream, environment, and properties This step is invisible. The source code is written.

4. Add, delete and modify annotations

When the method passes in multiple parameters, all parameters must be preceded by the annotation @ Param (), which is like a name, with the meaning of key. Therefore, when writing sql statements

@Param() is the main parameter, not the parameter name of the formal parameter. Similarly, if the parameters of the method are annotated, they are not annotated in mapper In XML, #{key} is in the brackets of * * @ param (), which should correspond to. If the parameter passed in is a reference object, you don't need to add @ param()

Adding, deleting and modifying require transaction submission, so automatic submission can be set in the tool class

public static SqlSession getSqlsession(){
return sqlSessionFactory.openSession(true);//Auto submit
}

4.1 add

Since the class used for mapper mapping writes methods in the same interface, it can be configured once. Here, only three steps are written: write methods in the interface; The method is annotated, and sql statements are written in the annotation; test

step1,2

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

step3

@Test
public void addUser(){
    SqlSession sqlsession = MybatisUtils.getSqlsession();
    UserMapper mapper = sqlsession.getMapper(UserMapper.class);
    mapper.addUser(new User(6,"zjy","475869"));
    sqlsession.close();
}

4.2 deletion

step1,2

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

step3

@Test
public void deleteUser(){
    SqlSession sqlsession = MybatisUtils.getSqlsession();
    UserMapper mapper = sqlsession.getMapper(UserMapper.class);
    mapper.deleteUser(6);
    sqlsession.close();
}

4.3 update

step1,2

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

step3

@Test
public void updateUser(){
    SqlSession sqlsession = MybatisUtils.getSqlsession();
    UserMapper mapper = sqlsession.getMapper(UserMapper.class);
    mapper.updateUser(new User(2,"zjjy","47582369"));
    sqlsession.close();
}

4.4@Param

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

  • When the method only accepts one parameter, you can not use @ Param. It is recommended to add it.
  • Basic type parameters or String type parameters need to be added
  • 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. The reference data type does not need to be added
  • When @ Param annotation is not used, there can only be one parameter and it is a java bean.
  • The attribute name set in the @ Param bracket is referenced in the sql statement

Other points for attention

#Difference from $

  • #The function of {} is mainly to replace the placeholder in the preparestatement? [recommended]

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

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

In fact, it's a pile of precompiled, sql injection and placeholders

Keywords: Mybatis Framework

Added by deezin on Thu, 10 Feb 2022 07:31:52 +0200