項目結(jié)構(gòu)如下:
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哩掺,它的作用就是解析配置(數(shù)據(jù)源、別名等) -->
<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>
這樣當(dāng)我們使用到mapper/*.xml的時候就會把我們調(diào)用的SQL語句輸出出來。這種方法對動態(tài)SQL的調(diào)試很有幫助。
【測試】
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>
<!--這里用了兩種大于配并、小于、大于等于高镐、小于等于的寫法溉旋,僅為練習(xí)-->
<select id="getEmpByCondition" parameterType="Map" resultMap="EmpMap">
select * from emp
<trim prefix="where" suffixOverrides="and">
<!--因篇幅過長,這里省略部分代碼-->
<!--工資區(qū)間-->
<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傳參數(shù)測試:
此時可以發(fā)現(xiàn)控制臺已經(jīng)輸出了SQL語句及我們傳入的參數(shù):