Struts2+MyBatis3.1.0+Spring3.1.0整合之道二SqlSessionTemplate

时间:2023-01-16 05:10:30

相关框架搭建在Struts2+MyBatis3.1.0+Spring3.1.0整合之道一 数据映射接口,已经讲解的非常详细,这里就不在讲述SSI框架的搭建。

 

(1)、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
               在mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。

               而在MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。
                SqlSessionFactoryBean有一个必须属性dataSource(数据源), 另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。

sping配置文件:

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 
	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-2.5.xsd
	 http://www.springframework.org/schema/context
	 http://www.springframework.org/schema/context/spring-context-2.5.xsd
	 http://www.springframework.org/schema/tx 
	 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
	 http://www.springframework.org/schema/aop 
	 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
	 "
	
	>
	 <!-- 采用注释的方式配置bean -->  
    <context:annotation-config />  
    <!-- 配置要扫描的包 -->  
    <context:component-scan base-package="com.vixuan.skydrive"></context:component-scan>  
      
    <!--proxy-target-class="true"强制使用cglib代理   如果为false则spring会自动选择-->  
   <aop:aspectj-autoproxy  proxy-target-class="true"/>  
   
	
<!--数据源配置  -->
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
 		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value> 		
 		</property>  
 		<property name="url">
 			<value>jdbc:mysql://127.0.0.1:3306/skydrive</value>		
 		</property>
 		<property name="username">
 				<value>root</value>
 		</property>
 		<property name="password">
 				<value>123456</value>
 		</property>
 		<property name="maxIdle">
			<value>40</value> 		
 		</property>
 		<property name="maxWait">
 			<value>40</value>
 		</property> 		
   </bean>
   <!--SqlSessionFactoryBean 配置  -->
  <span style="color:#ff0000;"> <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
   			<property name="configLocation">
   				<value>classpath:mybatis.xml</value>
   			</property>
   			<property name="dataSource">
   				<ref local="dataSource"></ref>
   			</property>
</span>   </bean>
  <span style="color:#ff0000;"><!-- 配置SqlSessionTemplate -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
	    <constructor-arg index="0" ref="SqlSessionFactory" />
	</bean>
</span>   
   <!--配置事务管理器  -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   		<property name="dataSource">
   		<ref local="dataSource"></ref>
   		</property>
   </bean>
   
     <!-- 使用annotation注解方式配置事务 -->  
    <tx:annotation-driven transaction-manager="transactionManager"/> 
    <bean id="impl" class="com.vixuan.skydrive.daoimpl.UserDaoImpl" autowire="byName">    
   	<span style="color:#ff0000;"><property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property></span> 
    </bean>
    
    <bean id="userService" class="com.vixuan.skydrive.serviceimpl.UserServiceImpl" autowire="byName" >   
    <property name="impl" ref="impl"></property> 
    </bean>
    
  
    
 
 

</beans>


 MyBatis配置文件:

<?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>
 <typeAliases>  
        <typeAlias alias="user" type="com.vixuan.skydrive.model.User"/>  
    </typeAliases>  
    <mappers>  
        <mapper resource="com/vixuan/skydrive/sqlmap/user.xml" />  
    </mappers> 

</configuration>	


实体类映射文件user.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="com.pdsu.edu.domain.User">
	
	<resultMap type="com.vixuan.skydrive.model.User" id="userResult">
		<result property="user" column="user"/>
		<result property="pass" column="pass" />
		<result property="xm" column="xm" />
		<result property="email" column="email"/>
		<result property="phone" column="phone" />
		<result property="qq" column="qq" />
	</resultMap>

	<select id="selectAllUser" resultMap="userResult">
		select * from t_user
 	</select>

	<select id="findUserById" parameterType="String" resultMap="userResult">
		select *
		from t_user where user=#{user}
 	</select>

	<insert id="insert" parameterType="user">
	 <![CDATA[
		insert into
		t_user(user,pass,xm,email,phone,qq) values(#{user},#{pass},#{xm},#{email},#{phone},#{qq})
		]]>
 	</insert>

	<update id="update" parameterType="user">
		update t_user set
		user=#{user},pass=#{pass} where xm=#{xm}
 	</update>
 	
	<delete id="delete" parameterType="String">
		delete from t_user where
		user=#{user}
	</delete>

</mapper>


dao层接口和dao层实现(daoImpl)

UserDao

package com.vixuan.skydrive.dao;

import java.util.List;

import com.vixuan.skydrive.model.User;

public interface UserDao {
	public abstract void insert(User dao);
	public abstract void update(User dao);
    public abstract void delte(User dao);
    public abstract User findById(String Id);
    public List<User> findAll();

}


UserDaoImpl

package com.vixuan.skydrive.daoimpl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.vixuan.skydrive.dao.UserDao;
import com.vixuan.skydrive.model.User;
@Repository 
public class UserDaoImpl implements UserDao {
	//sql 标识符
	private final String INSERT= "insert";  
    private final String UPDATE = "update";  
    private final String DELETE = "delete";  
    private final String FIND_USER_BYID = "findUserById";  
    private final String SELECT_ALL_USER = "selectAllUser";  
   //依赖注入
    @Autowired 
    private SqlSessionTemplate sqlSessionTemplate;
    //构造函数
    

public SqlSessionTemplate getSqlSessionTemplate() {
	return sqlSessionTemplate;
}
//
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
	this.sqlSessionTemplate = sqlSessionTemplate;
	}

	public void insert(User dao) {
		// TODO Auto-generated method stub
		sqlSessionTemplate.insert(INSERT, dao);
	}

	

	public void update(User dao) {
		// TODO Auto-generated method stub
		sqlSessionTemplate.update(UPDATE, dao);
	}

	public void delte(User dao) {
		// TODO Auto-generated method stub
		sqlSessionTemplate.delete(DELETE, dao);
	}

	public User findById(String Id) {
		// TODO Auto-generated method stub
		return sqlSessionTemplate.selectOne(FIND_USER_BYID, Id);
		
	}

	public List<User> findAll() {
		// TODO Auto-generated method stub
		return sqlSessionTemplate.selectList(SELECT_ALL_USER);
	}

}


server接口和serverimpl实现

UserServer:

package com.vixuan.skydrive.service;

import java.util.List;

import com.vixuan.skydrive.model.User;

public interface UserService {
	public abstract void insert(User dao);
	public abstract void update(User dao);
    public abstract void delte(User dao);
    public abstract User findById(String Id);
    public List<User> findAll();

}


UserServerImpl

package com.vixuan.skydrive.serviceimpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vixuan.skydrive.daoimpl.UserDaoImpl;
import com.vixuan.skydrive.model.User;
import com.vixuan.skydrive.service.UserService;
@Service  
@Transactional

public class UserServiceImpl implements UserService {
	//dao
	@Autowired 
    private UserDaoImpl impl;	

	public void insert(User dao) {
		// TODO Auto-generated method stub
		impl.insert(dao);
	}

	public void update(User dao) {
		// TODO Auto-generated method stub
		impl.update(dao);
	}

	public void delte(User dao) {
		// TODO Auto-generated method stub
		impl.delte(dao);
	}

	public UserDaoImpl getImpl() {
		return impl;
	}
//
	public void setImpl(UserDaoImpl impl) {
		this.impl = impl;
}

	public User findById(String Id) {
		// TODO Auto-generated method stub
		User user=impl.findById(Id);
		return user;
	}

	public List<User> findAll() {
		// TODO Auto-generated method stub
		List<User> list=impl.findAll();
		return list;
	}

}


逻辑层action

UserAction

package com.vixuan.skydrive.action;

import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.vixuan.skydrive.model.User;
import com.vixuan.skydrive.serviceimpl.UserServiceImpl;
@Controller  
@Scope("prototype")  

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
    private User user;  
    private List<User> userList;
    private static UserServiceImpl userService;

    @Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	



	public static UserServiceImpl getUserService() {
		return userService;
	}





	public static void setUserService(UserServiceImpl userService) {
		UserAction.userService = userService;
	}





	public String add() { 
	
       userService.insert(user);  
        return SUCCESS;  
    }  
  
    public String delete() {  
        userService.delte(user);  
        return SUCCESS;  
    }  
  
    public String update() {  
        userService.update(user);  
        return SUCCESS;  
    }  
    //set 和  get

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
    


}


相关页面:(add.jsp、update.jsp和delete.jsp)

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@ taglib prefix="s"  uri="/struts-tags"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>添加新用户</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">     
  
  </head>  
    
  <body>  
    <center>  
        <h1>添加新用户</h1>  
        <s:form action="user_add" namespace="/user" method="post">  
            <s:textfield label="用户名" name="user.user"></s:textfield>  
            <s:password label="密码" name="user.pass"></s:password>  
            <s:textfield label="姓名" name="user.xm"></s:textfield>
            <s:textfield label="邮箱" name="user.email"></s:textfield>
            <s:textfield label="电话" name="user.phone"></s:textfield>
            <s:textfield label="qq" name="user.qq"></s:textfield>
            <s:submit value="提交"></s:submit>  
        </s:form>  
    </center>  
  </body>  
</html>  


delete.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@ taglib prefix="s"  uri="/struts-tags"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>添加新用户</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">     
  
  </head>  
    
  <body>  
    <center>  
        <h1>添加新用户</h1>  
        <s:form action="user_delete" namespace="/user" method="post">   
         <s:textfield label="用户名" name="user.user"></s:textfield>             
            <s:submit value="提交"></s:submit>  
        </s:form>  
    </center>  
  </body>  
</html>  


update.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@ taglib prefix="s"  uri="/struts-tags"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
      
    <title>修改用户</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">     
  
  </head>  
    
  <body>  
    <center>  
        <h1>修改用户</h1>  
        <s:form action="user_update" namespace="/user" method="post">  
            <s:hidden name="user.xm"></s:hidden>  
            <s:textfield label="用户名" name="user.user"></s:textfield>  
            <s:password label="密码" name="user.pass"></s:password>  
            <s:submit value="提交"></s:submit>  
        </s:form>  
    </center>  
  </body>  
</html>  


Struts.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="authority" extends="struts-default">  
<!-- 定义一个拦截器 -->  
        <interceptors>  
            <interceptor name="authority"  
                class="com.vixuan.skydrive.interceptot.LoginInterceptor">  
            </interceptor>  
            <!-- 拦截器栈 -->  
            <interceptor-stack name="mydefault">  
                <interceptor-ref name="defaultStack" />  
                <interceptor-ref name="authority" />  
            </interceptor-stack>  
        </interceptors>          
        <!-- 定义全局Result -->  
        <global-results>  
            <!-- 当返回login视图名时,转入/login.jsp页面 -->  
            <result name="login">/login.jsp</result>  
        </global-results>
        
        <action name="login" class="com.vixuan.skydrive.action.LoginAction">  
            <result name="success">/welcome.jsp</result>  
            <result name="error">/login.jsp</result>  
            <result name="input">/login.jsp</result>  
        </action>         
         <action name="show" class="com.vixuan.skydrive.action.ShowAction">  
            <result name="success">/show.jsp</result>  
            <!-- 使用此拦截器 -->  
            <interceptor-ref name="mydefault" />  
        </action>          
</package>
	<constant name="struts.i18n.encoding" value="UTF-8"/>  
            <!-- 指定默认编码集 ,作用于HttpServletRequest的setCharacterEncoding()和freemarker,vilocity的输出 -->  
    <constant name="struts.configuration.xmlreload" value="true"/>  
            <!-- 当struts配置文件修改时是否自动加载 -->  
    <constant name="struts.devMode" value="false"/>  
            <!-- 开发模式下打印详细的错误信息 -->  
    <constant name="struts.ui.theme" value="xhtml"/>  
      
    <package name="users" namespace="/user" extends="struts-default">  
        <action name="user_*" class="com.vixuan.skydrive.action.UserAction" method="{1}">  
            <result name="success">/index.jsp</result>             
        </action>  
    </package>  
    
    <package name="struts2.action" extends="struts-default">
    <action name="loginUser" class="com.vixuan.skydrive.action.LoginActions">
    </action>
	</package>
    


</struts>    


项目结构图:

Struts2+MyBatis3.1.0+Spring3.1.0整合之道二SqlSessionTemplate