地址:http://takeme.iteye.com/blog/1736320
MyBatis3.1.1+Spring3.1.2+Struts2.3.4.1
先來看目錄結構來看配置文件
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>