mybatis 使用SqlsessionDaoSupport 调用sql,如此,不需要配置mapper包扫描,可以将接口与sql映射文件放入不同的文件夹。
1.需要使用的jar包
2.web.xml配置
<!-- 设置spring字符编码过滤器 -->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring启动的监听 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置struts2启动过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.ApplicationContext.xml 配置
<!-- 配置外部数据库连接信息-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 配置sqlsessionfactory -->
<bean id="sqlsessionfactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务 -->
<!-- 1.配置事务管理器 -->
<bean id="transManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2.配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 3.配置切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.ibatis.service.*.*(..))" />
</aop:config>
<!-- 将sqlSessionTemplate手工注入到SqlSessionDaoSupport中 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlsessionfactory"/>
</bean>
<!-- 导入相关配置 -->
<import resource="classpath:spring/applicationContext-dao.xml"/>
<import resource="classpath:spring/applicationContext-service.xml"/>
<import resource="classpath:spring/applicationContext-action.xml"/>
4.applicationContext-dao.xml配置
<!-- 继承SqlSessionDaoSupport类,使用mybatis底层封装的方法,需要注入sqlSessionTemplate -->
<bean id="mybatisPersistence" class="com.ibatis.mapper.impl.MybatisPersistenceImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<!-- 继承了工具类,需要注入工具类注入的属性sqlsessionTemplate 如果不继承,调用工具类的接口则无需注入SqlSessionDaoSupport的属性sqlSessionTemplate-->
<bean id="mybatisDao" class="com.ibatis.dao.impl.MybatisDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
<!-- <property name="mybatisPersistence" ref="mybatisPersistence"></property> -->
</bean>
5.applicationContext-service.xml配置
<bean id="mybatisService" class="com.ibatis.service.impl.MybatisServiceImpl">
<property name="mybatisDao" ref="mybatisDao"></property>
</bean>
7.applicationContext-action.xml配置
<bean id="mybatisAction" class="com.ibatis.action.MybatisAction">
<property name="mybatisService" ref="mybatisService"></property>
</bean>
8.db.properties 外部数据源配置
jdbc.url=jdbc:mysql:///activitiwebporject?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
9.sqlMapConfig.xml的配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置sql路径 -->
<mappers>
<mapper resource="application\testMybatis.xml"/>
<mapper resource="application\AEmployee.xml"/>
</mappers>
</configuration>
10.struts.xml<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 配置模式为开发模式,自动加载struts.xml和显示错误提示信息 -->
<constant name="struts.devMode" value="true" />
<!-- 设置页面主题为简单主题,去掉struts2开发提供的样式 -->
<!-- <constant name="struts.ui.theme" value="simple" /> -->
<package name="default" namespace="/" extends="struts-default">
<!-- 拦截器配置 -->
<!-- <interceptors>
定义了一个用于拦截器登录的拦截器
<interceptor name="loginInterceptor" class="com.ibatis.utils.LoginInteceptor"></interceptor>
定义一个拦截器栈
<interceptor-stack name="systemStack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="loginInterceptor" />
</interceptor-stack>
</interceptors> -->
<!-- 定义系统默认拦截器 全局 -->
<!-- <default-interceptor-ref name="systemStack" /> -->
<!-- 全局结果视图 -->
<global-results>
<result name="login" type="redirect">
login.jsp
</result>
</global-results>
<action name="select_*" class="mybatisAction" method="{1}">
<result name="show">WEB-INF/jsp/show.jsp</result>
</action>
</package>
</struts>
11.使用SqlSessionDaoSupport定义工具方法
package com.ibatis.mapper.impl;
import java.lang.reflect.Array;
import java.util.List;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.ibatis.mapper.MybatisPersistence;
public class MybatisPersistenceImpl extends SqlSessionDaoSupport implements MybatisPersistence{
@Resource
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
super.setSqlSessionTemplate(sqlSessionTemplate);
}
/**
* 执行模板sql插入数据
* @param obj
*/
public void insertEntity(Object obj){
String sqlid = obj.getClass().getName()+".insertEntity";
this.getSqlSession().insert(sqlid,obj);
}
/**
* 执行模板sql更新数据
* @param obj
*/
public void updateEntity(Object obj){
String sqlid = obj.getClass().getName()+".updateEntity";
this.getSqlSession().update(sqlid, obj);
}
/**
* 执行模板sql三层数据
* @param obj
*/
public void delete(Object obj){
String sqlid = obj.getClass().getName()+".delete";
this.getSqlSession().delete(sqlid, obj);
}
/**
* clazz 返回值类型
* sqlId namespace+sqlId
* param 参数
*/
public <T> T[] findList(Class<?> clazz,String sqlId, Object param) throws Exception{
T[] dataObject = null;
List<?> list = this.getSqlSession().selectList(sqlId, param);
dataObject = list.toArray((T[]) Array.newInstance(clazz, list.size()));
return dataObject;
}
}
12.AEmployee.xml 单表模型sql
<?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="com.ibatis.pojo.Employee" >
<insert id="insertEntity" parameterType="com.ibatis.pojo.Employee" >
<![CDATA[
insert into a_employee (
name,
password,
email,
role
) values(
#{name},
#{password},
#{email},
#{role}
)
]]>
</insert>
<update id="updateEntity" parameterType="com.ibatis.pojo.Employee" >
update a_employee
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="role != null" >
role = #{role,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<delete id="delete" parameterType="com.ibatis.pojo.Employee" >
<![CDATA[
delete from a_employee where id = #{id}
]]>
</delete>
13.testMybatis.xml命名sql
<?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="com.mybatis" >
<select id="queryEmployee" resultType="com.ibatis.pojo.Employee" parameterType="java.util.Map">
select * from a_employee where id = #{id}
</select>
</mapper>