本文詳細記錄 Spring MVC 整合 MyBatis 的 DAO 層配置全過程,包含數據源、SqlSessionFactory、Mapper 掃描、逆向工程生成基礎 CRUD、自定義複雜查詢 Mapper 等核心內容。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://120.25.162.238:3306/mybatis001?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 類型別名批量掃描 -->
<typeAliases>
<package name="com.iot.learnssm.firstssm.po"/>
</typeAliases>
<!-- Mapper 由 Spring 整合包掃描,此處無需配置 -->
</configuration>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 載入屬性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 數據源 DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="30"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"/>
</bean>
<!-- Mapper 掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.iot.learnssm.firstssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
使用 MyBatis Generator 根據表結構生成:
Items)ItemsMapper)public class ItemsCustom extends Items {
// 可添加關聯查詢擴展屬性,如類別名、供應商等
}
public class ItemsQueryVo {
private Items items; // 原始查詢條件
private ItemsCustom itemsCustom; // 擴展查詢條件
// getter/setter 省略
}
public interface ItemsMapperCustom {
List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
<mapper namespace="com.iot.learnssm.firstssm.mapper.ItemsMapperCustom">
<!-- 動態 SQL 條件片段 -->
<sql id="query_items_where">
<if test="itemsCustom != null">
<if test="itemsCustom.name != null and itemsCustom.name != ''">
items.name LIKE '%${itemsCustom.name}%'
</if>
</if>
</sql>
<select id="findItemsList" parameterType="com.iot.learnssm.firstssm.po.ItemsQueryVo"
resultType="com.iot.learnssm.firstssm.po.ItemsCustom">
SELECT items.* FROM items
<where>
<include refid="query_items_where"/>
</where>
</select>
</mapper>
整合完成後的工程目錄清晰分層:po、mapper、service、controller、spring 配置文件各司其職,為後續 Service 與 Controller 開發奠定堅實基礎。