MyBatis: Use annotations development

Oriented programming interface

  • Before we all learned object-oriented programming, also studied interface, but in the real development, many times we will choose oriented programming interface
  • Root Cause: decoupling, can expand and improve reuse, layered development, do not control the upper concrete implementation, we have to comply with common standards, making the development easier, better normative
  • In an object-oriented system, the various functions of the system is composed of many different objects done in collaboration. In this case, each object inside is how to achieve their own, in terms of system designers is not so important;
  • The collaborative relationship between various objects is a key system design. Small to communication between different classes, as large as the interaction between the modules in the beginning of system design is an important consideration, which is the main tasks of system design. Oriented programming interface refers to the programming in accordance with this idea.

Understanding of the interface

  • The interface from the deeper understanding, should be defined (specification constraints) separate from the implementation (real name separated Principles).
  • Interface itself reflects the system designer to abstract understanding of the system.
  • There should be two types of interfaces:

    • The first class is an abstract of an individual, which may correspond to an abstract body (abstract class);
    • The second class is an abstract one aspect of a subject, i.e., an abstract form surface (interface);
  • You may have a body having a plurality of abstract faces. Abstractions and abstract plane is different.

Three for the difference

  • Object-oriented means that, when we consider the issue, units of objects, considering its properties and methods.
  • Process-oriented means that, when we consider the problem to a specific process (transaction process) as a unit, consider its implementation.
  • Interface design and interface design is for a non-multiplexing terms, with the object (process) is not facing a problem. More manifestation of the overall system architecture

Use annotations Development

  • mybatis initial configuration information is based on XML, mapping statement (SQL) is defined in XML. By MyBatis 3 provides a new annotation-based configuration. Unfortunately, Java annotations expressive power and flexibility is very limited. The most powerful MyBatis mapping annotations can not be built
  • sql type is divided into:

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

[Note] you do not need to use annotations development mapper.xml mapped files.

  1. We add annotations in our interface

    //查询全部用户
    @Select("select id,name,pwd password from user")
    public List<User> getAllUser();
  2. Injection mybatis core configuration file

    <!--使用class绑定接口-->
    <mappers>
        <mapper class="com.kuang.mapper.UserMapper"/> </mappers>
  3. We go test

    @Test
    public void testGetAllUser() { SqlSession session = MybatisUtils.getSession(); //本质上利用了jvm的动态代理机制 UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.getAllUser(); for (User user : users){ System.out.println(user); } session.close(); }
  4. Use Debug view nature
    1552373232920.png
  5. Jvm use of dynamic proxy mechanism in nature
    1567057042911.png
  6. Mybatis detailed implementation process
    20180507152553971.png

Notes CRUD

getSession tools of transformation MybatisUtils () method, heavy implement. [Chicken Soup: look at the source code to achieve]

//获取SqlSession连接
public static SqlSession getSession(){ return getSession(true); //事务自动提交 } public static SqlSession getSession(boolean flag){ return sqlSessionFactory.openSession(flag); }

[Note] ensure entity classes and a corresponding database fields

Inquire:

  1. Write interface method Notes

    //根据id查询用户
    @Select("select * from user where id = #{id}")
    User selectUserById(@Param("id") int id);
  2. 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(); }

Add:

  1. Write interface method Notes

    //添加一个用户
    @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
    int addUser(User user);
  2. test

    @Test
    public void testAddUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(6, "秦疆", "123456"); mapper.addUser(user); session.close(); }

modify:

  1. Write interface method Notes

    //修改一个用户
    @Update("update user set name=#{name},pwd=#{pwd} where id = #{id}")
    int updateUser(User user);
  2. test

    @Test
    public void testUpdateUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(6, "秦疆", "zxcvbn"); mapper.updateUser(user); session.close(); }

delete:

  1. Write interface method Notes

    //根据id删除用
    @Delete("delete from user where id = #{id}")
    int deleteUser(@Param("id")int id);
  2. test

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

[Note point: CRUD handling of affairs must remember]

About @Param

@Param notes for a name to the method parameter. The following is a summary of the use of principles:

  • In the case of the method takes a single parameter, it may not be used @Param.
  • In the case of method accepts multiple parameters, proposals must be annotated to use @Param parameter name.
  • If the argument is a JavaBean, you can not use @Param.
  • When not in use @Param notes, only one parameter, and is Javabean.

#With $distinction

  • #{} The main function is to replace a prepared statement (PrepareStatement) placeholders? [Recommended]

    INSERT INTO user (name) VALUES (#{name}); INSERT INTO user (name) VALUES (?);
  • Action is $ {} string replacement directly

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

Guess you like

Origin www.cnblogs.com/wpy188/p/12375444.html