mapper
将sql映射注册到全局配置中,这个我们在上一章已经使用过了,
-
resource
这个属性是用来引用类路径下的sql映射文件
-
url
这个属性是用来引用网络路径或磁盘路径下的sql映射文件
-
class
直接引用接口(注册接口),这里需要把接口和映射文件放在同一文件夹下,而且要保证,两者同名。
如果你是使用IDEA,这里需要大家注意一件事,由于新版的IntelliJ IDEA不再编译source folder下的xml文件,而我们平时使用mybatis时,习惯于将*Mapper.xml文件放在与dao层、service层平级的src目录下。这就导致ItelliJ IDEA不会变异这些xml文件夹,从而导致Invalid bound statement (not found)的发生。
我们需要在pom.xml文件的<build>标签加入以下代码:
-
<resources>
-
<resource>
-
<directory>src/main/java</directory>
-
<includes>
-
<include>**/*.xml</include>
-
</includes>
-
</resource>
-
</resources>
当然还有一种方法∑(っ°Д°;)っ:
mybatis是支持没有sql映射文件,所有的sql都是利用注解写在接口上:
-
package com.figsprite.dao;
-
-
import com.figsprite.bean.Employee;
-
import org.apache.ibatis.annotations.Select;
-
-
public interface EmployeeMapperAnnotation {
-
@Select("select id,last_name lastName,gender,email from tb_employee where id = #{id}")
-
Employee getEmpById(Integer id);
-
}
-
@Test
-
public void test2() throws IOException {
-
SqlSession openSession = getSqlSessionFactory().openSession();
-
-
try {
-
EmployeeMapperAnnotation employee = openSession.getMapper(EmployeeMapperAnnotation.class);
-
employee.getEmpById(1);
-
System.out.println(employee);
-
}finally {
-
openSession.close();
-
}
-
}
这种方式比较简单,但是违背了Mybatis的初衷——抽离sql语句,建议比较重要的sql写在xml文件里,而比较简单的,我们就写在java代码里。
-
如果我们的接口中有很多种方法对应sql语句,那么,我们一句一句sql写起来是不是很麻烦?因此Mybatis提供了批量注册的标签package
与别名中的package使用相同
<package name="包名"/>
可想而知,注解版的mapper是没有问题的,但是通过xml文件配置的,就会有问题了,因此必须要放在同包下,并且同名。
-
<mappers>
-
<package name="com.figsprite.dao"/>
-
</mappers>
另外强调一点,全局配置文件中的这些标签是有顺序要求的,不按顺序些会报错