Mybatis CRUD operations based on annotations

table of Contents

Use annotations to implement CRUD operations

@Param () annotation

The disadvantages of using annotations to write CRUD operations

Compare # {} $ {} Difference


 

Use annotations to implement CRUD operations

 

This method is essentially supported by the reflection mechanism, and the bottom layer implements a dynamic proxy

In simple terms, it only takes two steps. The first step is to add CRUD annotations and SQL to the Dao interface; the second step is to bind the interface registration to the core configuration file

public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    // 方法存在多个参数,所有的参数前面必须加上 @Param("id")注解
    @Select("select * from user where id = #{id}")
    User getUserByID(@Param("id") int id);


    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);

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

    
    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
}
    <mappers>
        <mapper class="com.lt.dao.UserDao"/>
    </mappers>

When calling, just write the calling method normally, the main function is to omit the mapper.xml file

    @Test
    public void test(){
        //获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }
        logger.info("查询成功啦~");
        //关闭SqlSession
        sqlSession.close();
    }

 

 

@Param () annotation

 

The @Param () annotation is used to map entity attributes and fields in the table. There are the following precautions when using

  • Basic type parameters or String type, need to add

  • Other reference types do not need to be added

  • If there is only one basic type, it can be ignored, but it is recommended that everyone add it!

  • What we quote in SQL is the attribute name set in @Param () here!

 

 

The disadvantages of using annotations to write CRUD operations

 

Simple SQL statements using annotations for CRUD will make the code appear more concise and the project structure clearer. But for complex SQL statements, using annotations can be confusing.

 

 

Compare # {} $ {} Difference

 

# {} Can prevent SQL injection, but $ {} cannot prevent  

Published 568 original articles · Like 180 · Visits 180,000+

Guess you like

Origin blog.csdn.net/Delicious_Life/article/details/105673401