MyBatis+Spring+Struts2

系统 1736 0
MyBatis3.1.1+Spring3.1.2+Struts2.3.4.1
先来看目录结构
MyBatis+Spring+Struts2

MyBatis+Spring+Struts2

来看配置文件
applicationContext.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"  
    xmlns:context="http://www.springframework.org/schema/context"   
    xsi:schemaLocation="http://www.springframework.org/schema/context   
     http://www.springframework.org/schema/context/spring-context-3.0.xsd    
     http://www.springframework.org/schema/beans   
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
     http://www.springframework.org/schema/tx   
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 

<!-- 采用c3p0数据源 这个是在企业中用的比较多的一个数据源 -->  
<!-- destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->  
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
   <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>  
   <property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>  
   <property name="user" value="luob"/>  
   <property name="password" value="luob"/>  
   <!-- 连接池中的最大连接数 -->  
   <property name="maxPoolSize" value="150"/>  
     
   <!-- 连接池中的最小连接数 -->  
   <property name="minPoolSize" value="1"></property>  
     
   <!-- 初始化连接池中的 连接数,取值 在  minPoolSize 和 maxPoolSize 之间,default:3-->  
   <property name="initialPoolSize" value="3"/>  
     
   <!-- 最大空闲时间,60s内该连接没有被使用则被丢弃,若为0 永不丢弃.default:0 -->  
   <property name="maxIdleTime" value="60"/>  
     
   <!-- 当连接数不够时,每次同时创建多少个连接 -->  
   <property name="acquireIncrement" value="1"/>  
     
   <!-- 每60s检查连接池中的所有空间连接,如果没有被使用,就被放弃, default:0 -->  
   <property name="idleConnectionTestPeriod" value="60"/>  
</bean> 

  <!-- 从c3p0数据源中抽取出JDBC的代理对象-->  
<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.C3P0NativeJdbcExtractor"  lazy-init="true" />   
  
<!--9i: org.springframework.jdbc.support.lob.OracleLobHandler  -->  
<!--10g以后:org.springframework.jdbc.support.lob.DefaultLobHandler(mysql,DB2等都可以用这个)  -->  
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true">  
  <!-- 9i: 指定操作lob类型数据的jdbc代理对象 如果上面的 lobHandler 换了下面的就不需要了 -->  
  <property name="nativeJdbcExtractor">  
    <ref local="nativeJdbcExtractor" />  
  </property>  
</bean> 

<!-- 使用jdbc 来管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置 mybatis 的sqlSessionFactory 由 spring 的 SqlSessionFactoryBean 代理 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

<!-- 使用spring 的 SqlSessionTemplate 创建一个 可以批量操作的sqlSession  -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
	<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>


<!-- =============================== -->
<!--  /////////    dao 的配置              /////-->
<!-- =============================== -->
<bean id="studentDAO" class="com.mybatis.student.IStudentDAOImpl">
	<property name="sqlSession" ref="sqlSession"/>
</bean>

<!-- 使用   sqlSessionTemplate 创建的 sqlSession -->
<bean id="studentDAO1" class="com.mybatis.student.IStudentDAOImpl_sqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

<bean id="studentDAO2" class="com.mybatis.student.IStudentDAOImpl_sqlSessionDaoSupport">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	<!-- 或者 使用   sqlSessionTemplate  如果两个都配置了 会忽略 sqlSessionFactory -->
</bean>

<!-- 采用MapperFactoryBean  -->
<bean id="classesDAO" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<property name="mapperInterface" value="com.mybatis.classes.IClassesDAO"/>
	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- =============================== -->
<!--  /////   Serivce 的配置                /////-->
<!-- =============================== -->
<bean id="studentService" class="com.mybatis.student.IStudentServiceImpl">
	<property name="sudentDAO" ref="studentDAO"/>
</bean>

<bean id="classesService" class="com.mybatis.classes.IClassesServiceImpl">
	<property name="classesDAO" ref="classesDAO"/>
</bean>

</beans>   

  


mybatis-config.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>

    <!-- 配置的元素顺序 properties?, settings?, typeAliases?, typeHandlers?, 
    objectFactory?, objectWrapperFactory?, proxyFactory?, plugins?, 
    environments?, databaseIdProvider?, mappers -->
     
    <!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->  
    <settings>  
        <!-- 全局映射器启用缓存 -->  
        <setting name="cacheEnabled" value="true" />  
        <!-- 查询时,关闭关联对象即时加载以提高性能 -->  
        <setting name="lazyLoadingEnabled" value="true" />  
        <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->  
        <setting name="aggressiveLazyLoading" value="false" />  
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->  
        <setting name="multipleResultSetsEnabled" value="true" />  
        <!-- 允许使用列标签代替列名 -->  
        <setting name="useColumnLabel" value="true" />  
        <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->  
        <!-- <setting name="useGeneratedKeys" value="true" /> -->  
        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->  
        <setting name="autoMappingBehavior" value="FULL" />  
        <!-- 对于批量更新操作缓存SQL以提高性能 -->  
        <setting name="defaultExecutorType" value="SIMPLE" />  
        <!-- 数据库超过25000秒仍未响应则超时 -->  
        <setting name="defaultStatementTimeout" value="25000" />  
    </settings>   
     
    <!-- 使用属性文件 而且可以在这里这是 覆盖文件中的值 -->
   
	
    <!-- 别名的配置 -->
    <typeAliases>
		<typeAlias type="com.mybatis.student.Student" alias="Student"/>
		<typeAlias type="com.mybatis.classes.Classes" alias="Classes"/>
		<!-- 
			也可以使用 包范围来配置
			<package name="com.mybatis"/>
		 -->
	</typeAliases>
	
	<!-- 环境的配置 -->
	
	<!-- 映射文件的配置 -->
	<mappers>
		<mapper resource="com/mybatis/student/StudentMapper.xml"/>
		<mapper resource="com/mybatis/classes/ClassesMapper.xml"/>
	</mappers>
	
</configuration>

  


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>
	<package name="student" namespace="/student" extends="struts-default">
		<action name="allStudent" class="com.mybatis.action.StudentAction" method="getAllStudent">
			<result name="success">/index.jsp</result>
		</action>
		<action name="updateAndSelect" class="com.mybatis.action.StudentAction" method="getAllStudentAfterupdate">
			<result name="success">/index.jsp</result>
		</action>
		<action name="delStudentById" class="com.mybatis.action.StudentAction" method="delStudentById">
			<result name="success">/index.jsp</result>
		</action>
	</package>
	
	<package name="classes" namespace="/classes" extends="struts-default">
		<action name="queryClassesById" class="com.mybatis.action.ClassesAction" method="queryClassesById">
			<result name="success">/index1.jsp</result>
		</action>
		<action name="delClassesById" class="com.mybatis.action.ClassesAction" method="delClassesById">
			<result name="success">/index1.jsp</result>
		</action>
	</package>
</struts>

  


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">
	
	<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>
	<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>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  


--映射文件
StudentMapper.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.mybatis.student">
   	<!-- <!ELEMENT mapper (
   		cache-ref | cache | resultMap* | parameterMap* | sql* 
   		| insert* | update* | delete* | select* )+> -->
   	
   	<!-- 设置缓存 如果用户需要登录 需要设置这种类型 type=org.mybatis.caches.oscache.LoggingOSCache-->
    <cache eviction="FIFO" readOnly="true" size="256" flushInterval="60000"/>
     
    <!-- 定义可以重用的sql 代码片段  -->
 	<sql id="studentColumns">sid,sname,score</sql>

	<!-- 自定义结果集 --> 	
 	<resultMap type="Student" id="studentResultMap">
 		<id property="sid" column="SID"/>
 		<result property="sname" column="SNAME"/>
 		<result property="score" column="SCORE"/>
 	</resultMap>
 	
 	<resultMap type="Student" id="studentAllResultMap">
 		<id property="sid" column="SID"/>
 		<result property="sname" column="SNAME"/>
 		<result property="major" column="MAJOR"/>
 		<result property="birth" column="BIRTH"/>
 		<result property="score" column="SCORE"/>
 		<result property="cid" column="CID"/>
 		<result property="status" column="STATUS"/>
 	</resultMap>
 	
 	<!-- 只用构造函数 创建对象 对于那些 比较少的列 -->
 	<resultMap type="Student" id="studentAndClassesResultMap">
 		<constructor>
 			<idArg column="SID" javaType="int"/>
 			<arg column="SNAME" javaType="String"/>
 			<arg column="SCORE" javaType="float"/>
 		</constructor>
 		<association property="classes" javaType="Classes" resultMap="com.mybatis.classes.classesResultMap"/>
 	</resultMap>
 
 
 	<select id="selectStudentAndClassBySname" parameterType="String" resultMap="studentAndClassesResultMap">
 		select s.sid,s.sname,s.score,c.cid,c.cname,c.teacher,c.createdate from student s left join classes c on s.cid=c.cid where s.sname=#{sname}
 	</select>
 
 	<insert id="addStudentBySequence" parameterType="Student" >
 	<selectKey keyProperty="sid" resultType="int" order="BEFORE">
 		select STUDENT_SEQ.nextVal from dual
 	</selectKey>
 		insert into student(sid,sname,major,birth,score)
    	values (#{sid},#{sname},#{major},#{birth},#{score})
 	</insert>
 	
 	<insert id="addStudent" parameterType="Student">
 		insert into student(sid,sname,major,birth,score)
 		values (#{sid},#{sname},#{major},#{birth},#{score})
 	</insert>
 	
 	<delete id="delStudentById" parameterType="int">
 		delete student where sid=#{sid}
 	</delete>
 	
 	<select id="queryAllStudent" resultType="Student" useCache="true" flushCache="false" timeout="10000">
 		select * from student order by sid
 	</select>
 	
 	<!-- 参数可以指定一个特定的数据类型  还可以使用自定类型处理: typeHandler=MyTypeHandler -->
 	<select id="queryStudentByName" resultType="Student" parameterType="String">
 		select * from student where sname like #{property,javaType=String,jdbcType=VARCHAR}
 	</select>
 	
 	<!-- 参数可以指定一个特定的数据类型 对于数字类型 ,numericScale=2  用于设置小数类型  -->
 	<select id="queryStudentById" resultType="Student" parameterType="int">
 		select * from student where sid=#{property,javaType=int,jdbcType=NUMERIC}
 	</select>
 	
 	
 	<update id="updStudentById" parameterType="Student">
 		update student 
 		<trim prefix="SET" suffixOverrides=",">
 			<if test="sname !=null">sname=#{sname},</if>
 			<if test="major !=null">majoir=#{major},</if>
 			<if test="birth !=null">birth=#{birth},</if>
 			<if test="score !=null">score=#{score}</if>
 		</trim>
 		where sid=#{sid}
 	</update>
 	
 	<!-- 在这里 利用了 可重用的sql代码片段 -->
 	<select id="selectMapResult" resultMap="studentResultMap" parameterType="String">
 		select <include refid="studentColumns"/> from STUDENT where sname like #{sname}
 	</select>	
 	
 	<!-- Dynamic  Sql 使用  if -->
 	<select id="selectStudentByDynamicSql" parameterType="Student" resultType="Student">
 		select * from student 
 		<where>
	 		<if test="sname !=null">
	 			sname like #{sname}
	 		</if>
	 		<if test="sid !=null">
	 			AND sid=#{sid}
	 		</if>
 		</where>
 	</select>
 	
 	<!-- 采用 OGNL 表达式  来配置动态sql 使用trim 去掉 where 中多余的  and 或者 or  where  choose  when otherwise-->
 	<select id="selectStudentByDynamicSqlChoose" parameterType="Student" resultType="Student">
 		select * from student 
 		<trim prefix="WHERE" prefixOverrides="AND | OR ">
 			<choose>
 				<when test=" sname !=null and sname.length() >0 "> 
 					sname like #{sname}
 				</when>
 				<when test="sid !=null and sid>0">
 					AND sid = #{sid}
 				</when>
 				<otherwise>
 					AND status='1'
 				</otherwise>
 			</choose>
 		</trim>
 	</select>
 	
 	<!-- 使用foreach 遍历list  只能小写-->
 	<select id="selectStudentByIds" resultType="Student">
 		select * from student 
 		where sid in
 		<foreach collection="list" item="itm" index="index" open="(" separator="," close=")">
 			#{itm}
 		</foreach>
 	</select>
 	
 	<!-- 使用foreach 遍历arry 只能小写 -->
 	<select id="selectStudentByIdArray" resultType="Student">
 		select * from student 
 		where sid in
 		<foreach collection="array" item="itm" index="index" open="(" separator="," close=")">
 			#{itm}
 		</foreach>
 	</select>
 	
 	<parameterMap type="map" id="procedureParam">
 		<parameter property="sid" javaType="int" jdbcType="NUMERIC" mode="IN" />
 		<parameter property="sname" javaType="String" jdbcType="VARCHAR" mode="IN" />
 		<parameter property="studentList" javaType="ResultSet" jdbcType="CURSOR" mode="OUT" resultMap="studentAllResultMap"/> 
 	</parameterMap>
 	<!--传入map集合参数 ,调用  待用游标存储过程(先执行 修改后然后查询所有)  -->
 	<select id="getAllStudentAfterupdate" statementType="CALLABLE" useCache="false" parameterMap="procedureParam">
 		{call LUOB.pro_getallstudent(?,?,?)}
 	</select>

 </mapper>

  


ClassesMapper.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">
 
 <!--注意:
    1. 这里的 namespace 要指定到 mapperInterface 的 接口类的路径 
    2. 这里的 statement 的id 要和 接口类中的 方法名一样
 -->
 <mapper namespace="com.mybatis.classes.IClassesDAO">
 	
 	<!-- 设置 缓存共享 -->
 	<cache-ref namespace="com.mybatis.student"/>
 	
 	<resultMap type="Classes" id="classesResultMap">
 		<id column="CID" property="cid"/>
 		<result column="CNAME" property="cname"/>
 		<result column="TEACHER" property="teacher"/>
 		<result column="CREATEDATE" property="createDate"/>
 	</resultMap>
 	
 	<!-- columnPrefix:别名前缀 -->
 	<resultMap type="Classes" id="classesAndStudentListResultMap">
 		<id column="CID" property="cid"/>
 		<result column="CNAME" property="cname"/>
 		<result column="TEACHER" property="teacher"/>
 		<result column="CREATEDATE" property="createDate"/>
 		<collection property="students" ofType="Student" resultMap="com.mybatis.student.studentResultMap" columnPrefix="stu_"/>
 	</resultMap>
 	
 	<!-- 下面采用了 别名 stu_ 来区分列名 -->
 	<select id="selectClassAndStudentListById" resultMap="classesAndStudentListResultMap" parameterType="int">
 		select 
	 		c.cid,
	 		c.cname,
	 		c.teacher,
	 		c.createdate,
	 		s.sid stu_sid,
	 		s.sname stu_sname,
	 		s.score stu_score
 		from student s right join classes c on s.cid=c.cid where c.cid=#{cid}
 	</select>
 	
 	<delete id="delClassesBycid" parameterType="int">
 		delete classes where cid=#{cid}
 	</delete>
 	
 </mapper>

  


--dao 和 impl
IStudentDAO.java
    
package com.mybatis.student;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.mybatis.classes.Classes;

/**
 * 手动写dao 然后注入sqlSession 或者 继承
 * @author Administrator
 *
 */
public interface IStudentDAO {
	//手动添加 id
	public int addStudent(Student student);

	//自动生成 id
	public int addStudentBySequence(Student student);

	//根据id删除
	public int delStudentById(int id);
	
	//测试更新
	public int updStudentById(Student student);

	//查询所有
	public List<Student> queryAllStudent();

	//测试 模糊查询
	public List<Student> queryStudentByName(Student name);

	//测试 id查询
	public Student queryStudentById(int id);
	
	//测试 自定义 resultMap
	List<Student> studentResultMap(String sname);
	
	//测试 左连接查询
	List<Student> selectStudentAndClassBySname(String sname);

	//测试 右联合查询
	Classes selectClassAndStudentListById(int id);
	
	//测试动态sql
	List<Student> selectStudentByDynamicSql(Student student);
	
	//测试动态sql
	List<Student> selectStudentByDynamicSqlChoose(Student student);
	
	//测试 foreach 和集合
	List<Student> selectStudentByIds(ArrayList<Integer> ids);
	
	//测试 foreach 和 数组
	List<Student> selectStudentByIdArray(Integer[] idArry);
	
	//测试 map
	Map getAllStudentAfterupdate(Map map);
	
}


  


IStudentDAOImpl.java
    
package com.mybatis.student;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

import com.mybatis.classes.Classes;

/**
 *  @author Administrator
 *  如果要直接使用 mybatis 的 sqlSession 不由spring 管理 sqlSession 
 *  可以只注入sqlSessionFactory 然后 像mybatis 中使用 sqlSession 一样  openSession()  .close() 
 *  否则  可以 继承 SqlSessionDaoSupport ("getSqlSession() insert/select/delete/update")
 *  和  SqlSessionTemplate 得到 spring 管理的 线程安全的 sqlSession 
 *  或者 简单的使用XML中配置  MapperFactoryBean 这样就省去了我们 获取sqlSession了 
 */
public class IStudentDAOImpl implements IStudentDAO {

	private SqlSessionTemplate sqlSession;
	
	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}
	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}
	
	public int addStudent(Student student) {
		// TODO Auto-generated method stub
		
		return getSqlSession().insert("com.mybatis.student.addStudent", student);
		
	}

	public int addStudentBySequence(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().insert("com.mybatis.student.addStudentBySequence", student);
	}

	public int delStudentById(int id) {
		int rows=getSqlSession().delete("com.mybatis.student.delStudentById", id);
		System.out.println(rows);
		return rows;
	}

	public List<Student> queryAllStudent() {
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.queryAllStudent");
		return stuList;
	}

	public Student queryStudentById(int id) {
		// TODO Auto-generated method stub
		return (Student)getSqlSession().selectOne("com.mybatis.student.queryStudentById",id);
	}

	public Map getAllStudentAfterupdate(Map map) {
		// TODO Auto-generated method stub
		 getSqlSession().selectOne("com.mybatis.student.getAllStudentAfterupdate",map);
		 return map;
	}

	public Classes selectClassAndStudentListById(int id) {
		// TODO Auto-generated method stub
		return (Classes)getSqlSession().selectOne("com.mybatis.classes.selectClassAndStudentListById",id);
	}

	public List<Student> selectStudentAndClassBySname(String sname) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.selectStudentAndClassBySname",sname);
		return stuList;
	}

	public List<Student> selectStudentByDynamicSql(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByDynamicSql",student);
	}

	public List<Student> selectStudentByDynamicSqlChoose(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByDynamicSqlChoose",student);
	}

	public List<Student> selectStudentByIdArray(Integer[] idArry) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByIdArray",idArry);
	}

	public List<Student> selectStudentByIds(ArrayList<Integer> ids) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByIds",ids);
	}

	public List<Student> studentResultMap(String sname) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectMapResult",sname);
	}

	public List<Student> queryStudentByName(Student name) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.queryStudentByName","%"+name+"%");
		return stuList;
	}

	public int updStudentById(Student student) {
		return getSqlSession().update("com.mybatis.student.addStudentBySequence", student);
	}

}


  


IStudentDAOImpl_sqlSessionDaoSupport.java
    
package com.mybatis.student;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.mybatis.classes.Classes;

/**
 *  @author Administrator
 *  如果要直接使用 mybatis 的 sqlSession 不由spring 管理 sqlSession 
 *  可以只注入sqlSessionFactory 然后 像mybatis 中使用 sqlSession 一样  openSession()  .close() 
 *  否则  可以 继承 SqlSessionDaoSupport ("getSqlSession() insert/select/delete/update")
 *  和  SqlSessionTemplate 得到 spring 管理的 线程安全的 sqlSession 
 *  或者 简单的使用XML中配置  MapperFactoryBean 这样就省去了我们 获取sqlSession了 
 */
public class IStudentDAOImpl_sqlSessionDaoSupport  extends SqlSessionDaoSupport  implements IStudentDAO {

	public int addStudent(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().insert("com.mybatis.student.addStudent", student);
	}

	public int addStudentBySequence(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().insert("com.mybatis.student.addStudentBySequence", student);
	}

	public int delStudentById(int id) {
		int rows=getSqlSession().delete("com.mybatis.student.delStudentById", id);
		System.out.println(rows);
		return rows;
	}

	public List<Student> queryAllStudent() {
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.queryAllStudent");
		return stuList;
	}

	public Student queryStudentById(int id) {
		// TODO Auto-generated method stub
		return (Student)getSqlSession().selectOne("com.mybatis.student.queryStudentById",id);
	}

	public Map getAllStudentAfterupdate(Map map) {
		// TODO Auto-generated method stub
		 getSqlSession().selectOne("com.mybatis.student.getAllStudentAfterupdate",map);
		 return map;
	}

	public Classes selectClassAndStudentListById(int id) {
		// TODO Auto-generated method stub
		return (Classes)getSqlSession().selectOne("com.mybatis.classes.selectClassAndStudentListById",id);
	}

	public List<Student> selectStudentAndClassBySname(String sname) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.selectStudentAndClassBySname",sname);
		return stuList;
	}

	public List<Student> selectStudentByDynamicSql(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByDynamicSql",student);
	}

	public List<Student> selectStudentByDynamicSqlChoose(Student student) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByDynamicSqlChoose",student);
	}

	public List<Student> selectStudentByIdArray(Integer[] idArry) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByIdArray",idArry);
	}

	public List<Student> selectStudentByIds(ArrayList<Integer> ids) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectStudentByIds",ids);
	}

	public List<Student> studentResultMap(String sname) {
		// TODO Auto-generated method stub
		return getSqlSession().selectList("com.mybatis.student.selectMapResult",sname);
	}

	public List<Student> queryStudentByName(Student name) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=getSqlSession().selectList("com.mybatis.student.queryStudentByName","%"+name+"%");
		return stuList;
	}

	public int updStudentById(Student student) {
		return getSqlSession().update("com.mybatis.student.addStudentBySequence", student);
	}

}

  


IStudentDAOImpl_sqlSessionTemplate.java
    
package com.mybatis.student;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.mybatis.classes.Classes;

/**
 *  @author Administrator
 *  如果要直接使用 mybatis 的 sqlSession 不由spring 管理 sqlSession 
 *  可以只注入sqlSessionFactory 然后 像mybatis 中使用 sqlSession 一样  openSession()  .close() 
 *  否则  可以 继承 SqlSessionDaoSupport ("getSqlSession() insert/select/delete/update")
 *  和  SqlSessionTemplate 得到 spring 管理的 线程安全的 sqlSession 
 *  或者 简单的使用XML中配置  MapperFactoryBean 这样就省去了我们 获取sqlSession了 
 */
public class IStudentDAOImpl_sqlSessionTemplate extends SqlSessionTemplate implements IStudentDAO {

	//同样是 创建一个 可以批量操作的 sqlSession
	public IStudentDAOImpl_sqlSessionTemplate(
			SqlSessionFactory sqlSessionFactory) {
		super(sqlSessionFactory);
		// TODO Auto-generated constructor stub
	}

	public int addStudent(Student student) {
		// TODO Auto-generated method stub
		
		return this.insert("com.mybatis.student.addStudent", student);
		
	}

	public int addStudentBySequence(Student student) {
		// TODO Auto-generated method stub
		return this.insert("com.mybatis.student.addStudentBySequence", student);
	}

	public int delStudentById(int id) {
		int rows=this.delete("com.mybatis.student.delStudentById", id);
		System.out.println(rows);
		return rows;
	}

	public List<Student> queryAllStudent() {
		List<Student> stuList=new ArrayList<Student>();
		stuList=this.selectList("com.mybatis.student.queryAllStudent");
		return stuList;
	}

	public Student queryStudentById(int id) {
		// TODO Auto-generated method stub
		return (Student)this.selectOne("com.mybatis.student.queryStudentById",id);
	}

	public Map getAllStudentAfterupdate(Map map) {
		// TODO Auto-generated method stub
		 this.selectOne("com.mybatis.student.getAllStudentAfterupdate",map);
		 return map;
	}

	public Classes selectClassAndStudentListById(int id) {
		// TODO Auto-generated method stub
		return (Classes)this.selectOne("com.mybatis.classes.selectClassAndStudentListById",id);
	}

	public List<Student> selectStudentAndClassBySname(String sname) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=this.selectList("com.mybatis.student.selectStudentAndClassBySname",sname);
		return stuList;
	}

	public List<Student> selectStudentByDynamicSql(Student student) {
		// TODO Auto-generated method stub
		return this.selectList("com.mybatis.student.selectStudentByDynamicSql",student);
	}

	public List<Student> selectStudentByDynamicSqlChoose(Student student) {
		// TODO Auto-generated method stub
		return this.selectList("com.mybatis.student.selectStudentByDynamicSqlChoose",student);
	}

	public List<Student> selectStudentByIdArray(Integer[] idArry) {
		// TODO Auto-generated method stub
		return this.selectList("com.mybatis.student.selectStudentByIdArray",idArry);
	}

	public List<Student> selectStudentByIds(ArrayList<Integer> ids) {
		// TODO Auto-generated method stub
		return this.selectList("com.mybatis.student.selectStudentByIds",ids);
	}

	public List<Student> studentResultMap(String sname) {
		// TODO Auto-generated method stub
		return this.selectList("com.mybatis.student.selectMapResult",sname);
	}

	public List<Student> queryStudentByName(Student name) {
		// TODO Auto-generated method stub
		List<Student> stuList=new ArrayList<Student>();
		stuList=this.selectList("com.mybatis.student.queryStudentByName","%"+name+"%");
		return stuList;
	}

	public int updStudentById(Student student) {
		return this.update("com.mybatis.student.addStudentBySequence", student);
	}

}

  


IClassesDAO.java
    
package com.mybatis.classes;

/**
 * 使用  MapperFactoryBean 来管理 sqlSession 
 * @author Administrator
 *
 */
public interface IClassesDAO {
	// 也可以在这里使用注解配置 sql语句  这样就不用写 映射文件了
	Classes selectClassAndStudentListById(int cid);
	int delClassesBycid(int cid);
}


  


Student.java
    
package com.mybatis.student;

import java.io.Serializable;
import java.util.Date;

import com.mybatis.classes.Classes;

public class Student implements Serializable {
private int sid;
private String sname;
private String major;
private Date birth;
private float score;
private int cid;
private int status;

//get set()
}

  


Classes.java
    
package com.mybatis.classes;

import java.sql.Date;
import java.util.List;

import com.mybatis.student.Student;

public class Classes {
	private int cid;
	private String cname;
	private String teacher;
	private Date createDate;

	private List<Student> students;
	//get set
}

  


BaseAction.java
    
package com.mybatis.common;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport{

	public Object getServiceBean(String beanId){
		ServletContext sc=ServletActionContext.getServletContext();
		WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(sc);
		return ctx.getBean(beanId);
	}
	
	public HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	public Map<String, Object> getSession() {
		ActionContext act=ActionContext.getContext();
		return act.getSession();
	}
}

  


StudentAction.java
    
package com.mybatis.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.mybatis.common.BaseAction;
import com.mybatis.student.IStudentService;
import com.mybatis.student.Student;

public class StudentAction extends BaseAction {

	private Student student;
	private List<Student> stuList;
	
	public String getAllStudent(){
		try {
			IStudentService stuService=(IStudentService)this.getServiceBean("studentService");
			stuList=stuService.queryAllStudent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String delStudentById(){
		try {
			HttpServletRequest request=this.getRequest();
			IStudentService stuService=(IStudentService)this.getServiceBean("studentService");
			int rows=stuService.delStudentById(student.getSid());
			if(rows>0){
				request.setAttribute("msg", "<script type='text/javascript'>alert('删除成功!');</script>");
			}else{
				request.setAttribute("msg", "<script type='text/javascript'>alert('删除失败!');</script>");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return getAllStudent();
		
	}
	
	public String queryStudentById(){
		try {
			IStudentService stuService=(IStudentService)this.getServiceBean("studentService");
			student=stuService.queryStudentById(student.getSid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String getAllStudentAfterupdate(){
		try {
			Map map=new HashMap();
			map.put("sid", student.getSid());
			map.put("sname", student.getSname());
			IStudentService stuService=(IStudentService)this.getServiceBean("studentService");
			map=stuService.getAllStudentAfterupdate(map);
			stuList=(List<Student>)map.get("studentList");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	
	public List<Student> getStuList() {
		return stuList;
	}

	public void setStuList(List<Student> stuList) {
		this.stuList = stuList;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
	
	
}


  


ClassesAction.java
    
package com.mybatis.action;

import javax.servlet.http.HttpServletRequest;

import com.mybatis.classes.Classes;
import com.mybatis.classes.IClassesService;
import com.mybatis.common.BaseAction;

public class ClassesAction extends BaseAction {

	private Classes classes;
	
	/**
	 * 根据 id 删除
	 * @return
	 */
	public String delClassesById(){
		try {
			HttpServletRequest request=this.getRequest();
			IClassesService classesService=(IClassesService)this.getServiceBean("classesService");
			int rows=classesService.delClassesBycid(classes.getCid());
			if(rows>0){
				request.setAttribute("msg", "<script type='text/javascript'>alert('删除成功!');</script>");
			}else{
				request.setAttribute("msg", "<script type='text/javascript'>alert('删除失败!');</script>");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	/**
	 * 测试 右连接查询  会查询出 班级中拥有的学生 
	 * @return
	 */
	public String queryClassesById(){
		try {
			IClassesService classesService=(IClassesService)this.getServiceBean("classesService");
			classes=classesService.selectClassAndStudentListById(classes.getCid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	public Classes getClasses() {
		return classes;
	}
	public void setClasses(Classes classes) {
		this.classes = classes;
	}
	
}

  


index.jsp
    
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>MyBatis3.11 + Spring3.1.2 + Struts2</title>
  </head>
  
  <body>
  	 <form action="${pageContext.request.contextPath}/student/updateAndSelect.action" method="post">
     	<table cellpadding="0" cellspacing="0" bgcolor="#F4F4F4">
     		<tr>
     			<td>学生id</td>
     			<td><input type="text" name="student.sid"/></td>
     		</tr>
     		<tr>
     			<td>学生姓名</td>
     			<td><input type="text" name="student.sname"/></td>
     		</tr>
     	</table>
     	<input type="submit" value="修改姓名后测试procedure"/>
     </form>
     <input type="button" onclick="window.location.href='${pageContext.request.contextPath}/student/allStudent.action'" value="获取所有学生"/><br/>
     <c:if test="${fn:length(stuList)>0}">
     <table style="border: 1px solid blue;" border="1px" cellspacing="0" bgcolor="#F4F4F4">
     	<tr align="center">
     		<td width="100px">sid</td>
     		<td width="100px">sname</td>
     		<td width="100px">major</td>
     		<td width="150px">birth</td>
     		<td width="100px">score</td>
     		<td width="100px">操作</td>
     	</tr>
     	<c:forEach items="${stuList}" var="student">
     	<tr>
     		<td width="100px">${student.sid}</td>
     		<td width="100px">${student.sname}</td>
     		<td width="100px">${student.major}</td>
     		<td width="180px"><fmt:formatDate value="${student.birth}" pattern="yyyy-MM-dd HH:mm:ss"/><br></td>
     		<td width="100px">${student.score}</td>
     		<td><input type="button" onclick="window.location.href='${pageContext.request.contextPath}/student/delStudentById.action?student.sid=12'" value="删除"/> </td>
     	</tr>
     </c:forEach>
     </table>
     </c:if>
     ${msg}
  </body>
</html>


  


index1.jsp
    
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>MyBatis3.11 + Spring3.1.2 + Struts2</title>
  </head>
  
  <body>
  	 <form action="${pageContext.request.contextPath}/classes/queryClassesById.action" method="post">
     	<table cellpadding="0" cellspacing="0" bgcolor="#F4F4F4">
     		<tr>
     			<td>班级id</td>
     			<td><input type="text" name="classes.cid"/></td>
     		</tr>
     	</table>
     	<input type="submit" value="查询"/>
     </form>
     <input type="button" onclick="window.location.href='${pageContext.request.contextPath}/classes/allStudent.action'" value="获取所有学生"/><br/>
     <table style="border: 1px solid blue;" border="1px" cellspacing="0" bgcolor="#F4F4F4">
     	<tr>
     		<td width="100px">cid</td>
     		<td width="100px">cname</td>
     		<td width="100px">teacher</td>
     		<td width="100px">crateDate</td>
     		<td width="100px">操作</td>
     	</tr>
     	<tr>
     		<td>${classes.cid}</td>
     		<td>${classes.cname}</td>
     		<td>${classes.teacher}</td>
     		<td>${classes.createDate}</td>
     		<td width="100px"><input type="button" onclick="window.location.href='${pageContext.request.contextPath}/classes/delClassesById.action?classes.cid=12'" value="删除"/> </td></td>
     	</tr>
     <c:if test="${fn:length(classes.students)>0}">
     	<tr align="center">
     		<td width="100px">sid</td>
     		<td width="100px">sname</td>
     		<td width="150px">birth</td>
     		<td width="100px">score</td>
     		<td width="100px"></td>
     	</tr>
     	<c:forEach items="${classes.students}" var="student">
     	<tr>
     		<td width="100px">${student.sid}</td>
     		<td width="100px">${student.sname}</td>
     		<td width="180px"><fmt:formatDate value="${student.birth}" pattern="yyyy-MM-dd HH:mm:ss"/><br></td>
     		<td width="100px">${student.score}</td>
     		<td><input type="button" onclick="window.location.href='${pageContext.request.contextPath}/student/delStudentById.action?student.sid=12'" value="删除"/> </td>
     	</tr>
     </c:forEach>
     </c:if>
      </table>
     ${msg}
  </body>
</html>

  

MyBatis+Spring+Struts2


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论