1.引入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency> <!--spring的版本是5.0.9,mybatis-spring的版本要是1.3+ -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
2.在springmvc-config.xml增加mybatis配置
<!-- 针对myBatis的配置项 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描classpath:mapper/*.xml -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- 配置扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描com.ice.dao这个包以及它的子包下的所有映射接口类,省去了在每个mapper接口上注解 -->
<property name="basePackage" value="com.ice.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
3.在classpath:mapper/ 创建CustomerMapper.xml
注意创建的位置,是在上面设置的 mapperLocations.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace要跟后面该xml对应的mapper类的全名一致 -->
<mapper namespace="com.ice.dao.CustomerMapper">
<!-- id设置为mapper类对应的方法名, parameterType跟方法的参数类型一致,resultType跟方法的返回类型一致.
如果返回单个对象,mybatis会自动调用selectOne方法;如果返回的是List,mybatis会自动调用selectList方法.
-->
<select id="getUser" parameterType="java.lang.String"
resultType="com.ice.model.Customer">
select id,name from customer where name=#{name}
</select>
</mapper>
4.创建CustomerMapper.xml对应的CustomerMapper.java
注意创建的位置,是在上面设置的 basePackage.
package com.ice.dao; import com.ice.model.Customer;
//不用在xml里配置该bean,也不用注解.已经配置了MapperScanner
//<property name="basePackage" value="com.ice.dao" />
public interface CustomerMapper { Customer getUser(String name);
}
5.简单测试(在controller里测试,也可考虑springTest)
正式项目里,要有service层.
package com.ice.controller; import com.ice.dao.CustomerMapper;
import com.ice.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/mybatis")
public class MybatisController { @Autowired
private CustomerMapper customerMapper; @RequestMapping("/query")
@ResponseBody
public String index() {
Customer user = customerMapper.getUser("hello");
return "顾客id" + user.getId();
}
}