环境:jdk1.7 spring3.2.2 struts2.3.15 mybatis3.2.2 druid1.0.9.jar
上一篇文章我们学习了SSM整合,这里继续来讲解SSM整合之面向接口编程方式。
面向接口编程需要注意两个要点
1. mapper映射文件里的命名空间必须是【包名.接口名】的方式
2. 接口里面的方法名和映射文件里面的标签id值一致。
下面就来看看完整的案例
一 面向接口编程方式一
导入包
目录结构
关键代码
=============================web.xml==============================
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<error-page>
<error-code>404</error-code>
<location>/Err404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/Err500.html</location>
</error-page>
<!--struts2 config start -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,configs/struts.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--struts2 config end -->
<!-- druid pool -->
<filter>
<filter-name>DruidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DruidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<!--http://localhost:8080/SSHFinal/druid/index.html -->
<!--spring config start -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:configs/context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring config end -->
<!-- 加载日志start -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:configs/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 加载日志end -->
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
=====================context.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 导入其它sping配置文件 -->
<import resource="classpath:configs/spring/context-*.xml"/>
<!-- durid连接池配置start -->
<bean id="duridConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configs/druid.properties</value>
</list>
</property>
</bean>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="filters" value="${filters}" />
<property name="initialSize" value="${initialSize}" />
<property name="maxActive" value="${maxActive}" />
<property name="minIdle" value="${minIdle}" />
<property name="maxWait" value="${maxWait}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}" />
<property name="removeAbandoned" value="${removeAbandoned}" />
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
</bean>
<!-- durid连接池配置end -->
<!-- spring整合mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="druidDataSource"></property>
<property name="configLocation">
<value>classpath:configs/mybatis-config.xml</value>
</property>
<property name="mapperLocations">
<list>
<value>classpath:configs/mappers/*.xml</value>
</list>
</property>
</bean>
<bean id="sqlTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- 事务配置start -->
<bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDataSource"></property>
</bean>
<tx:advice id="txAdvise" transaction-manager="txManger">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="do*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="mycut" expression="execution(* com.obtk.biz.*.*(..))"/>
<aop:advisor advice-ref="txAdvise" pointcut-ref="mycut"/>
</aop:config>
<!-- 事务配置end -->
</beans>
===================其中的一个映射文件UserMapper.xml======================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"mybatis-3-mapper.dtd">
<mapper namespace="com.obtk.dao.IUserDao">
<cache></cache>
<select id="isLoginSuccess" parameterType="hashmap" resultType="UserEntity">
select * from users where userName=#{userName} and passWord=#{pwd}
</select>
<select id="isUserExists" parameterType="string" resultType="UserEntity">
select * from users where userName=#{userName}
</select>
<insert id="saveUser" parameterType="UserEntity"
useGeneratedKeys="true" keyProperty="userId">
insert into users(userName,passWord,email) values(#{userName},#{passWord},#{email})
</insert>
</mapper>
=============其中的一个接口IUserDao====================
package com.obtk.dao;
import java.util.HashMap;
import com.obtk.entitys.UserEntity;
public interface IUserDao {
UserEntity isLoginSuccess(HashMap<String, String> theMap);
UserEntity isUserExists(String userName);
Integer saveUser(UserEntity user);
}
=============其中的业务类UserBiz================
package com.obtk.biz;
import java.util.HashMap;
import org.mybatis.spring.SqlSessionTemplate;
import com.obtk.dao.IUserDao;
import com.obtk.entitys.UserEntity;
public class UserBiz {
private SqlSessionTemplate sqlTemplate;
public void setSqlTemplate(SqlSessionTemplate sqlTemplate) {
this.sqlTemplate = sqlTemplate;
}
public boolean isLoginSuccess(String userName, String passWord) {
IUserDao userDao=sqlTemplate.getMapper(IUserDao.class);
HashMap<String, String> theMap=new HashMap<String, String>();
theMap.put("userName", userName);
theMap.put("pwd", passWord);
UserEntity user= userDao.isLoginSuccess(theMap);
if(user!=null){
return true;
}else{
return false;
}
}
public boolean isUserExists(String userName) {
IUserDao userDao=sqlTemplate.getMapper(IUserDao.class);
UserEntity theUser= userDao.isUserExists(userName);
if(theUser!=null){
return true;
}else{
return false;
}
}
public Integer saveUser(UserEntity user) {
IUserDao userDao=sqlTemplate.getMapper(IUserDao.class);
return userDao.saveUser(user);
}
}
====================业务层的spring配置代码spring-biz.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="userBiz" class="com.obtk.biz.UserBiz" >
<property name="sqlTemplate" ref="sqlTemplate"></property>
</bean>
<bean id="stuBiz" class="com.obtk.biz.StudentBiz" >
<property name="sqlTemplate" ref="sqlTemplate"></property>
</bean>
<bean id="acctBiz" class="com.obtk.biz.AcctBiz">
<property name="sqlTemplate" ref="sqlTemplate"></property>
</bean>
</beans>
其它代码请参考我的博文SSM整合一!二 面向接口编程方式二
dao的实例在spring的配置里面完成! mybatis-spring提供了一个MapperFactoryBean,可以将数据映射接口转为SpringBean。
如下:
======================spring-dao.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.obtk.dao.IUserDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="stuDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.obtk.dao.IStudentDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="acctDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.obtk.dao.IAcctDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
==================业务层spring配置代码spring-biz.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="userBiz" class="com.obtk.biz.UserBiz" >
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="stuBiz" class="com.obtk.biz.StudentBiz" >
<property name="stuDao" ref="stuDao"></property>
</bean>
<bean id="acctBiz" class="com.obtk.biz.AcctBiz">
<property name="acctDao" ref="acctDao"></property>
</bean>
</beans>
===================业务层java代码之UserBiz.java==================
package com.obtk.biz;
import java.util.HashMap;
import org.mybatis.spring.SqlSessionTemplate;
import com.obtk.dao.IUserDao;
import com.obtk.entitys.UserEntity;
public class UserBiz {
private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public boolean isLoginSuccess(String userName, String passWord) {
HashMap<String, String> theMap=new HashMap<String, String>();
theMap.put("userName", userName);
theMap.put("pwd", passWord);
UserEntity user= userDao.isLoginSuccess(theMap);
if(user!=null){
return true;
}else{
return false;
}
}
public boolean isUserExists(String userName) {
UserEntity theUser= userDao.isUserExists(userName);
if(theUser!=null){
return true;
}else{
return false;
}
}
public Integer saveUser(UserEntity user) {
return userDao.saveUser(user);
}
}