映射器(mappers)
既然 MyBatis 的行為已經由上述元素配置完了,我們現在就要定義 SQL 映射語句了。但是首先我們需要告訴 MyBatis 到哪里去找到這些語句。
Java 在自動查找這方面沒有提供一個很好的方法,所以最佳的方式是告訴 MyBatis 到哪里去找映射文件。你可以使用相對於類路徑的資源引用, 或完全限定資源定位符(包括 file:/// 的 URL),或類名和包名等。例如:
<!-- 使用相對於類路徑的資源引用 --> <mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> <mapper resource="org/mybatis/builder/BlogMapper.xml"/> <mapper resource="org/mybatis/builder/PostMapper.xml"/> </mappers>
<!-- 使用完全限定資源定位符(URL) --> <mappers> <mapper url="file:///var/mappers/AuthorMapper.xml"/> <mapper url="file:///var/mappers/BlogMapper.xml"/> <mapper url="file:///var/mappers/PostMapper.xml"/> </mappers>
<!-- 使用映射器接口實現類的完全限定類名 --> <mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> <mapper class="org.mybatis.builder.BlogMapper"/> <mapper class="org.mybatis.builder.PostMapper"/> </mappers>
<!-- 將包內的映射器接口實現全部注冊為映射器 --> <mappers> <package name="org.mybatis.builder"/> </mappers>
1/前兩種 適用於 將sql寫入到 xml文件中
2/后兩種
(兩種方式進行映射的,
1種為 將sql映射關系使用注解形式寫到接口文件中,
第2中方式為將接口對應的sql映射文件xxx.xml放置於與接口所在包相同目錄結構下,如果是maven結構那么就是可以放置在src/main/java, src/main/resource下,但必須是相同包路徑)
1.適用於 將sql使用注解的方式寫在接口中(參考:https://blog.csdn.net/qq_33371766/article/details/80398769)
public interface StudentMapper { @Insert("insert into t_student values(null,#{name},#{age})") public int insertStudent(Student student); @Update("update t_student set name=#{name},age=#{age} where id=#{id}") public int updateStudent(Student student); @Delete("delete from t_student where id=#{id}") public int deleteStudent(int id); @Select("select * from t_student where id=#{id}") public Student getStudentById(Integer id); @Select("select * from t_student") @Results( { @Result(id=true,column="id",property="id"), @Result(column="name",property="name"), @Result(column="age",property="age") } ) public List<Student> findStudents(); }