MyBatis: developing with annotations

Keywords: Session Programming Mybatis xml

Interface oriented programming

  • You have learned object-oriented programming and interface before, but in real development, we often choose interface oriented programming
  • Root cause: decouple, expand, improve reuse, in layered development, the upper layer doesn't need to care about the specific implementation, everyone abides by the common standards, making development easier and more standardized
  • In an object-oriented system, various functions of the system are completed by many different objects. In this case, it is not so important for the system designer how to realize their own objects;
  • And the cooperation among the objects becomes the key of system design. From the communication between different classes to the interaction between modules, we should pay more attention to it at the beginning of system design, which is also the main work of system design. Interface oriented programming refers to programming according to this idea.

Understanding of interfaces

  • The deeper understanding of interface is the separation of definition (specification, constraint) and Implementation (principle of separation of name and reality).
  • The interface itself reflects the system designer's abstract understanding of the system.
  • There are two types of interfaces:
    • The first is the abstraction of an individual, which can be mapped to an abstract class;
    • The second is the abstraction of a certain aspect of an individual, that is, to form an interface;
  • An individual may have multiple abstract aspects. Abstract body and abstract surface are different.

Three 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 refers to the realization of a specific process (transaction process) when we consider a problem
  • Interface design and non interface design are for reuse technology. They are not a problem with object-oriented (process). More embodiment is the overall architecture of the system

Develop with annotations

  • The initial configuration information of MyBatis is based on XML, and the mapping statement (SQL) is also defined in XML. MyBatis 3 provides a new annotation based configuration. Unfortunately, Java annotations have limited expressiveness and flexibility. The most powerful MyBatis mapping cannot be built with annotations

  • sql types are mainly divided into:

    • @select ()
    • @update ()
    • @Insert ()
    • @delete ()

Note: the mapper.xml mapping file is not needed for annotation development

  1. We add comments to our interface
//Query all users
@Select("select id,name,pwd password from user")
public List<User> getAllUser();
  1. Inject in the core configuration file of mybatis
<!--UseclassBinding interface-->
<mappers>
    <mapper class="com.zheng.mapper.UserMapper"/>
</mappers>
  1. Let's test it
@Test
public void testGetAllUser() {
    SqlSession session = MybatisUtils.getSession();
    //In essence, it makes use of the dynamic agent mechanism of jvm
    UserMapper mapper = session.getMapper(UserMapper.class);

   List<User> users = mapper.getAllUser();
    for (User user : users){
        System.out.println(user);
    }

    session.close();
}
  1. Using Debug to see the essence
  2. In essence, it makes use of the dynamic agent mechanism of jvm
  3. Detailed execution process of Mybatis

Addition, deletion and modification of notes

Modify the getSession() method of MybatisUtils tool class to overload the implementation. [chicken soup: see source code implementation more]

//Get SqlSession connection
public static SqlSession getSession(){
    return getSession(true); //Transaction auto commit
}

public static SqlSession getSession(boolean flag){
    return sqlSessionFactory.openSession(flag);
}

[note] ensure that the entity class corresponds to the database field

Query:

  1. Write interface method annotation
//Query users by id
@Select("select * from user where id = #{id}")
User selectUserById(@Param("id") int id);
  1. test
@Test
public void testSelectUserById() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    User user = mapper.selectUserById(1);
    System.out.println(user);

    session.close();
}

New:

  1. Write interface method annotation
//Add a user
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);
  1. test
@Test
public void testAddUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    User user = new User(6, "great", "123456");
    mapper.addUser(user);

    session.close();
}

Modified:

  1. Write interface method annotation
//Modify a user
@Update("update user set name=#{name},pwd=#{pwd} where id = #{id}")
int updateUser(User user);
  1. test
@Test
public void testUpdateUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    User user = new User(6, "great", "zxcvbn");
    mapper.updateUser(user);

    session.close();
}

Delete:

  1. Write interface method annotation
//Delete by id
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id")int id);
  1. test
@Test
public void testDeleteUser() {
    SqlSession session = MybatisUtils.getSession();
    UserMapper mapper = session.getMapper(UserMapper.class);

    mapper.deleteUser(6);
    
    session.close();
}

[Note: please remember to deal with the transaction when adding, deleting, modifying]

About @Param

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

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

#Difference from $

  • #The function of {} is mainly to replace the placeholder in the prepared statement
INSERT INTO user (name) VALUES (#{name});
INSERT INTO user (name) VALUES (?);
  • The purpose of ${} is to replace strings directly
INSERT INTO user (name) VALUES ('${name}');
INSERT INTO user (name) VALUES ('haoran');
34 original articles published, praised 0, and 266 visitors
Private letter follow

Posted by ammupon on Mon, 16 Mar 2020 22:35:24 -0700