MyBatis-- development using annotations

Life was very slow, it sucks to live, in addition to want you, I do everything else well.

Use annotations Development

1, oriented programming interface

The root cause-oriented programming interface: decoupling, scalability, increase reuse, layered development, the upper concrete implementations do not control, we have to comply with common standards, making the development easier, normative good

2, developed using annotations

  • Notes implemented on the interface

    @Select(value = "select * from user")
    List<User> getUsers();
  • Bind the interface to the core configuration file

    <!--绑定接口-->
    <mappers>
        <mapper class="rui.dao.UserMapper"/>
    </mappers>
  • test

    public class UserMapperTest {
        @Test
        public void test(){
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //底层主要应用反射
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getUsers();
            for (User user : users) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    }

    Essence: reflection mechanism to achieve

    Bottom: Dynamic Proxy

3、CRUD

We can automatically commit the transaction at the time of creation tools

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

Write interfaces, grow comment

public interface UserMapper {
    @Select(value = "select * from user")
    List<User> getUsers();

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

    @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);
}

Test category

[Note: we must want the interface registered to our core profile]

About @Param () comment

  • The basic argument of type String or type, we need to add
  • Reference types do not need to add
  • If only one of the basic types can be ignored, but it is recommended all together
  • We referenced in SQL is @Param we here attribute name set ()

$ # {} {} Difference

  • {} Is a pre-compiler process, the replacement string is $ {}

  • {#} mybatis processing time, will be in sql # {} with the number to call set assignment method PreparedStatement;? mybatis processing ${}time, it is to ${}replace the value of the variable
  • Use # {} can effectively prevent SQL injection, improve system security

Guess you like

Origin www.cnblogs.com/huangdajie/p/12443277.html