Mybatis basics (9) annotation programming

Mybatis basics (9) annotation development

public interface UserMapper{
    
    
    // 在不使用注解之前的方法是:写一个mapper配置文件,写对应的sql语句。在使用注解后直接在注解里写sql语句即可
    @Select("select * from user")
    <List> getAllUser();
}
  1. The method before not using annotations is: write a mapper configuration file and write the corresponding SQL statement. After using the annotation, you can write the sql statement directly in the annotation
  2. It turns out that the mapper mapping file is bound in conf, and then the interface is bound in the mapper mapping file. Now you can bind the interface directly in the conf file!

Mybatis is best to use the configuration file method, the annotation form can only be applied to relatively simple SQL statements, slightly more complex ones will not work (such as resultMap)

Annotation implements CRUD

We can automatically commit the transaction when the tool class is created!

// 使用openSession中参数为true,生成的session就会自动提交事务
SqlSession session = sqlSessionFactory.openSession(true);
// 这样使用这个session就可以实现自动提交,增删改不用commit了!

Inquire

public interface UserMapper{
    
    
    @select("select * from user")
    List<User> getUsers();
    
    @select("select * from user where uid=#{sid} and uname=#{name}")
    List<User> getUsers2(@Param("sid") int id, @Param("name") String name);
}
  • @Param annotations are annotations for parameters, and the parameter in the annotation is the name of the parameter. In other words: the parameters used in sql are the parameters in the annotations, not the actual parameter names!
  • Multiple parameters cannot be passed in without @Param, multiple parameters can only be passed in with @Param annotation!

increase

public interface UserMapper{
    
    
    @Insert("insert into user values (#{id}, #{name})")
    boolean insertUser(@Param("id") int id, @Param("name") String name);
}

modify

public interface UserMapper{
    
    
    @Update("update user set set name=#{name} where id=#{id}")
    boolean updateUser(@Param("id") int id, @Param("name") String name);
}

delete

public interface UserMapper{
    
    
    @Delete("delete from user where id=#{id} and name=#{name}")
    boolean deleteUser(@Param("id") int id. @Param("name") String name);
}

Guess you like

Origin blog.csdn.net/qq_43477218/article/details/113796574