项目结构如下:
1、配置mybatis配置文件
在mybatis-config.xml加入以下配置:
<configuration>
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
2、在applicationContext-database.xml中配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!--此处省略dataSource配置和sqlSessionTemplate配置-->
<!-- SqlSessionFactoryBean是一个工厂bean,它的作用就是解析配置(数据源、别名等) -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--把mybatis配置文件加入到SqlSessionFactory-->
<property name="configLocation" value="classpath:mapper/mybatis/mybatis-config.xml"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
</beans>
这样当我们使用到mapper/*.xml的时候就会把我们调用的SQL语句输出出来。这种方法对动态SQL的调试很有帮助。
【测试】
EmpDao.java:
@Repository
public class EmployeeDao {
@Resource
public SqlSession sqlSession;
public List<Employee> getEmpByCondition(Map<String,Object> map){
System.out.println(map.toString());
return sqlSession.selectList("mapper.EmpMapper.getEmpByCondition",map);
}
}
EmpMapper.xml:
<?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">
<mapper namespace="mapper.EmpMapper">
<resultMap type="com.EmpExercise.model.Employee" id="EmpMap" autoMapping="true">
<id property="empno" column="empno" />
<result property="ename" column="ename" />
<result property="job" column="job" />
<result property="hireDate" column="hireDate" />
<result property="salary" column="salary" />
<result property="deptno" column="deptno" />
</resultMap>
<!--这里用了两种大于、小于、大于等于、小于等于的写法,仅为练习-->
<select id="getEmpByCondition" parameterType="Map" resultMap="EmpMap">
select * from emp
<trim prefix="where" suffixOverrides="and">
<!--因篇幅过长,这里省略部分代码-->
<!--工资区间-->
<if test="beginSalary!=null or endSalary!=null">
<!--开始工资和初始工资相同-->
<choose>
<when test="beginSalary==endSalary">
salary =#{beginSalary} and
</when>
<when test="beginSalary!=endSalary">
salary >=#{beginSalary} and salary <=#{endSalary} and
</when>
<when test="beginSalary!=null and endSalary=null">
salary >=#{beginSalary} and
</when>
<when test="beginSalary=null and endSalary!=null">
salary <=#{endSalary} and
</when>
</choose>
</if>
</trim>
</select>
</mapper>
此处省略EmpService和EmpController的代码。下面直接用postman传参数测试:
此时可以发现控制台已经输出了SQL语句及我们传入的参数: