- 浏览: 1591882 次
- 来自: 上海
文章分类
- 全部博客 (374)
- Java (101)
- Struts (54)
- Oracle (30)
- JavaScript (16)
- Spring (27)
- Hibernate (16)
- MyEclipse (3)
- JSF (1)
- FreeMarker (2)
- SiteMesh (2)
- JfreeChart (2)
- Ibatis (2)
- JSP (12)
- MyBatis (4)
- SWFupload (1)
- EJB (4)
- Jboss (4)
- WebService (2)
- Linux (16)
- Android (2)
- XML (6)
- Java 网络编程 (13)
- AXIS2 (1)
- FTP (1)
- Jswing (1)
- Socket (3)
- 杂文选集 (6)
- solr (2)
- PS (1)
- Tomcat (7)
- JDBC (9)
- Highcharts (1)
- maven (1)
- Nodejs (0)
- navicat (2)
- Exception (5)
- eclipse (3)
- jQuery (1)
- springMVC (4)
- MySQL (11)
- SVN (1)
- Sql Server (1)
- zookeeper (1)
- JVM (1)
- Groovy (2)
- Git (1)
- Nginx (1)
- DynamicReport (1)
- IDEA (2)
- JasperReports (1)
- Postgresql (2)
- Mac (1)
- gradle (1)
- 数据结构算法 (1)
最新评论
-
hpu145:
引用引用
java 千分位的添加和去除 -
被遗忘的下路:
少了个junit-4.8.2的包
SSH2整合完整案例(四十三) -
白天看黑夜:
java过滤emoji字符处理,希望能帮到你http://ww ...
emoji 表情图片解决方法 -
caipeiming:
这个挺好JavaScript实现input输入框控件只允许输入 ...
js 控制文本框只能输入中文、英文、数字等 -
双子树:
东西太好啦受教啊
Struts2 JSP中将list,set ,Map传递到Action然后<s:iterator>遍历(三十五)
MyBatis3.1.1+Spring3.1.2+Struts2.3.4.1
先来看目录结构
来看配置文件
applicationContext.xml
mybatis-config.xml
struts.xml
web.xml
--映射文件
StudentMapper.xml
ClassesMapper.xml
--dao 和 impl
IStudentDAO.java
IStudentDAOImpl.java
IStudentDAOImpl_sqlSessionDaoSupport.java
IStudentDAOImpl_sqlSessionTemplate.java
IClassesDAO.java
Student.java
Classes.java
BaseAction.java
StudentAction.java
ClassesAction.java
index.jsp
index1.jsp
先来看目录结构
来看配置文件
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>
评论
3 楼
LHPig
2013-03-07
留名,等回来看。
2 楼
Luob.
2012-12-20
1 楼
xiaolongfeixiang
2012-12-19
如果配上数据库的建表情况,就更加完美了。
发表评论
-
spring-session 中的坑
2017-07-06 15:34 10000spring-session 配置 依赖 gradle ... -
Spring AspectJ Aop Annotation
2017-03-29 17:08 713import org.aspectj.lang.Proce ... -
MyBatis Generator配置文件context元素的defaultModelType属性
2014-11-25 10:00 3918MyBatis Generator配置文件context元素的 ... -
spring 第13天 使用@scheduled注解执行定时任务
2015-01-06 23:11 54098我们使用spring的注解 @Scheduled 执行定时任务 ... -
Spring 第12天,事务传播属性和 隔离级别
2014-09-28 00:36 8201 事务的传播属性(Propagation) 1) REQ ... -
spring 第11天 quartz任务调度
2014-08-24 13:59 1151Quartz是一个强大的企业级任务调度框架,Spring中继承 ... -
spring 第10 天 AOP 面向切面
2014-08-21 00:08 1756AOP(Aspect Orient Programming ... -
spring 第9天 Resurce 资源访问
2014-08-17 22:20 1876Spring Resource接口 spring提供的Reso ... -
spring 第8天 Spring 注解
2014-08-17 15:33 1476spring注解 @Component:标注一个普通的sp ... -
spring 第7天 Bean,BeanFactory处理器,配置器
2014-08-16 21:46 1243spring 两种后处理器 第一种,Bean 后处理器 对容器 ... -
spring 第6天SpEL,P命名空间,Util Schema
2014-08-13 22:52 1321使用p名称空间配置属性 ... -
spring 第5天不同作用域的bean,注入Field,方法返回值
2014-08-11 22:31 2119协调作用域不同步的bean 问题是;当一个singleton的 ... -
spring 第4天bean继承,init,destory-method
2014-08-10 17:54 1659深入理解Spring容器中的b ... -
spring 第3天使用java类和XML配置bean
2014-08-09 16:51 1510下面采用java类来配置bean,前面都采用xml进行配置be ... -
spring 第2天,bean作用域,自动注入集合
2014-08-06 22:16 1942sping容器中的Bean <!---beans的全 ... -
spring 第1天 IOC,DI,国际化,容器事件
2014-08-04 21:27 13991.构造注入(就是使用 构 ... -
解决getOutputStream() has already been called for this response
2014-07-30 19:16 3319java.lang.IllegalStateException ... -
SpringMVC 注解 和非注解
2014-01-26 10:29 18024首先看看非注解的项目结构 在web.xml文件 配置spr ... -
Struts2 + ajaxFileUpload 异步上传文件
2013-12-04 19:33 1891ajaxFileUpload下载地址http://www.ph ... -
详解spring 每个jar的作用
2013-11-19 23:54 3914spring.jar 是包含有完整 ...
相关推荐
MyBatis+Spring+Struts2 整合源码 修改下jdbc.properties就行了
mybatis+spring+struts2 使用oracle数据库 增删改查,是把csdn原先的mysql数据库改成oracle数据库,直接在myeclipse上导入就行,并添加数据库myuser表,还有id,username,password等字段,压缩包下又myuser用记事本...
Struts2、Spring和MyBatis是Java Web开发中经典的三大框架,它们分别负责MVC模式中的控制层、业务层和服务层。EasyUI则是一个基于jQuery的UI组件库,用于快速构建美观且响应式的Web应用界面。下面我们将深入探讨这三...
Struts+Spring+Mybatis+EasyUI(jQuery)注解案例。采用注解的方式跟踪代码依赖性,实现替代配置文件功能。里面包含了平时用的增删改查及分页,分页查询时用的是存储过程,提高了数据库的性能。代码简单、易懂。
【基于注解的Spring+Struts2+Mybatis+Maven项目详解】 在现代Web开发中,Spring、Struts2、Mybatis和Maven是四个非常重要的组件,它们各自负责不同的职责,共同构建了一个高效、灵活且易于维护的Java Web应用。这个...
2. 集成MyBatis:配置MyBatis的主配置文件,包括数据源、事务管理器、SqlSessionFactory和Mapper文件的位置。 3. 创建CXF服务:定义Web服务接口,实现该接口并配置到CXF中。CXF提供了基于注解的Web服务开发方式,...
Struts2、Spring和MyBatis是Java Web开发中经典的三大框架,它们组合起来可以构建出高效、可维护的Web应用程序。以下是对这三个框架及其整合的详细解释。 **Struts2框架** Struts2是一个基于MVC(Model-View-...
mybatis+spring+struts+maven实例.
标题 "spring+mybatis+struts" 暗示了我们正在讨论一个基于Java的Web开发框架集成,其中Spring作为核心容器,MyBatis作为持久层框架,而Struts则作为表现层框架。这种组合在过去的几年里非常流行,因为它提供了良好...
Struts2、MyBatis和Spring3是Java开发中常用的三大框架,它们分别负责MVC模式中的Action层、持久层和整体应用管理。这三者的整合可以构建出高效、灵活的企业级应用程序。以下是对这三个框架及其整合的详细解释: 1....
在现代的Web应用程序开发中,Java Web框架的组合使用已经成为了一种常见的模式,特别是Struts 2、Hibernate、MyBatis和Spring这四个组件的整合,它们分别在MVC架构的不同层面发挥着关键作用。本课程围绕这个组合展开...
Maven+Struts2+MyBatis+Spring搭建教程
Struts2、Maven、Spring和MyBatis是Java Web开发中的四大框架,它们的整合应用可以构建出高效、模块化的应用程序。这个实例是关于如何将这些技术融合在一起,实现一个用户注册的功能。 首先,Struts2是一个基于MVC...
【标题】"物流项目struts+mybatis+spring"是一个基于流行Java技术栈构建的物流管理系统。这个系统利用了Struts、MyBatis和Spring框架的强大力量,旨在实现高效、稳定且易于维护的物流业务流程管理。 【描述】提到的...
本项目"maven+struts2+spring+mybatis+springMVC"就是一个典型的Java Web应用开发组合,利用了这些框架的优势进行集成,实现了数据持久化、业务逻辑处理、视图展示以及依赖管理等多个层面的功能。 首先,我们来详细...
Struts2、Mybatis和Spring是Java开发中常用的三大开源框架,它们的整合可以构建一个高效、灵活的企业级应用系统。本实例将详细介绍如何通过注解方式实现这三者的集成,进行基本的增删改查操作。 首先,Struts2是MVC...
【标题】"Mybatis3+Spring4 +Struts2整合源码"是一个示例项目,展示了这三大流行Java Web框架的集成与协作。Mybatis3是轻量级的持久层框架,Spring4则是一个全面的企业级应用框架,而Struts2则作为MVC架构的一部分,...
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末...隐患排查系统源码+项目说明+数据库(基于Spring3.2+Struts2.3+Mybatis+Mysql5.7)...