mybatis 映射器(mappers) 配置说明 加载映射文件方式

映射器(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();
	
}
 
  

  

 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/hfultrastrong/p/10405247.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值