1, the CRUD

We can implement auto-commit transactions when the utility class is created!

public class MybatisUtils{ private static SqlSessionFactory sqlSessionFactory; Static {try{// SqlSessionFactory object String resource = "Mybatis -config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch(IOException e){ e.printStackTrace(); } } public static sqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); }}

2. Write interfaces

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

    @Select("select * from user where id=#{id}")
    User getUserById(@Param("id") int id);
    
    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
    int addUser(User user);

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

    @Delete(delete from user where id=#{uid})
    int deleteUser(@Param("uid") int id);
}

3. Write the core configuration file

<mappers>
    <mapper class="com.jialidun.dao.UserDao"/>
</mappers>

Note: we must bind the interface registry to our core configuration file!

Comments on @param (” XXX “)

  • Arguments to primitive types, or strings, need to be added
  • The reference type does not need to be added
  • If there is only one basic type, you can ignore it, but it is recommended to add!
  • What we are referring to in SQL is the attribute name set in @param (” XXX “)!

The difference between #{} and ${}

- #{} represents a placeholder symbol, using #{} to implement the PreparedStatement to set values to the placeholder, automatic Java and JDBC type conversion. - #{} can effectively prevent SQL injection. - #{} can receive simple type values or POJO property values. If parameterType transmits a single value of a simple type, the #{} parentheses can be value or some other name. - ${} can be used to concatenate the contents of parameterType into SQL without JDBC type conversion - ${} can receive simple type values or POJO property values. If parameterType transfers a single simple type value, ${} can only be value.