springMVC+mybatis

    最近要用springMVC+mybatis做一个项目,做了一番调查,在此作一小结。

    首先看配置,最先配起springMVC的监听:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>TeamMgr</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/spring/applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- listener below is created for testing database connection. -->
	<!-- <listener> -->
	<!-- <listener-class>ffcs.team.mgr.test.TestDB</listener-class> -->
	<!-- </listener> -->

	<listener>
		<listener-class>ffcs.team.mgr.web.utils.LoadOnStartUp</listener-class>
	</listener>

	<filter>
		<filter-name>sessionFilter</filter-name>
		<filter-class>ffcs.team.mgr.filter.SessionFilter</filter-class>
		<init-param>
			<param-name>excludeUrl</param-name>
			<param-value>/login/?|/static.*|/home.*|/index\.jsp|/login/auth/?</param-value>
		</init-param>
		<init-param>
			<param-name>redirectUrl</param-name>
			<param-value>/TeamMgr/login</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>sessionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring/springmvc-servlet.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<session-config>
	   <session-timeout>5</session-timeout>
	</session-config>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


    然后配置applicationContext.xml和springmvc-servlet.xml

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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="ffcs.team.mgr" />

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:config/props/jdbc.properties</value>
			</list>
		</property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>

	<!-- <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> -->
	<!-- <property name="dataSource" ref="dataSource"></property> -->
	<!-- <property name="configLocation" value="classpath:mybatis-config.xml"></property> -->
	<!-- </bean> -->

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:config/mybatis/mybatis-config.xml"></property>
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
	</bean>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<tx:annotation-driven transaction-manager="transactionManager" /> 

</beans>

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="ffcs.team.mgr">
	</context:component-scan>

	<mvc:resources location="/static/" mapping="/static/**" />

<!-- json配置 -->
		<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>
								text/html;charset=UTF-8
							</value>
						</list>
					</property>
				</bean>
				<!-- 启动JSON格式的配置 -->
				<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
					<!-- 解决 HttpMediaTypeNotAcceptableException: Could not find acceptable representation -->
					<property name="supportedMediaTypes">
						<list>
							<value>application/json;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>
	
	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

 	<bean id="exceptionResolver" 
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
 		<property name="exceptionMappings"> 
 		  <props> 
 		      <prop key="java.lang.Exception">common/error</prop> 
 		  </props> 
 		</property>
	</bean> 
	
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<property name="maxUploadSize" value="104857600"/>
		<property name="maxInMemorySize" value="4096"/>
	</bean>

</beans>


    到此,springmvc与数据库连接池配置完毕,现在开始配置mybatis,看applicationContext.xml里面指定了mybatis-config.xml文件的路径

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>
    <typeAliases>
        <package name="ffcs.team.mgr.entity"/>
    </typeAliases>
    <mappers>
        <mapper resource="config/mybatis/mapper/oracle/MenuMapper.xml"/>
        <mapper resource="config/mybatis/mapper/oracle/StaffMapper.xml"/>
        <mapper resource="config/mybatis/mapper/oracle/ProjectMapper.xml"/>
        <mapper resource="config/mybatis/mapper/oracle/StaffPrjMapper.xml"/>
        <mapper resource="config/mybatis/mapper/oracle/VersionMapper.xml"/>
        <mapper resource="config/mybatis/mapper/oracle/UserMapper.xml"/>
    </mappers>
</configuration>
其中,typeAliases节点会在指定包中扫描注解,读取类的别名。mapper节点指定详细mapper的位置。在此一ProjectMapper.xml为例。

ProjectMapper.xml

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ffcs.team.mgr.entity.Project">

    <resultMap type="Project" id="prjMap">  
        <id property="prjId" column="prj_Id" />  
        <result property="prjName" column="prj_Name" />  
        <result property="prjBackground" column="prj_Background" />  
        <result property="prjIncloduce" column="prj_introduce" />  
        <result property="isDel" column="is_Del" />  
        <result property="createTime" column="create_Time" />  
        <result property="updateTIme" column="update_TIme" />
        <association property="parentPrj" column="id=parent_prj" select="querySimplePrj" />
        <association property="currentVersion" column="id=prj_version" select="queryVersion" />
        <association property="createUser" column="id=create_User" select="querySimpleUser" />
        <association property="updateUser" column="id=update_User" select="querySimpleUser" />
    </resultMap>
    
    <resultMap type="User" id="simpleUserMap">
    	<id property="userId" column="user_Id" />  
        <result property="userName" column="user_Name" /> 
    </resultMap>

    <resultMap type="Version" id="versionMap">
    	<id property="versionId" column="version_Id" />  
        <result property="versionNum" column="version_num" /> 
        <result property="versionPath" column="version_path" /> 
    </resultMap>

    <resultMap type="Project" id="simplePrjMap">
    	<id property="prjId" column="prj_Id" />  
        <result property="prjName" column="prj_Name" /> 
    </resultMap>

	<!-- 查询版本信息 -->
    <select id="queryVersion" parameterType="java.util.Map" resultMap="versionMap">  
        select version_Id,version_num,version_path from t_version where version_Id=#{id}
    </select> 
    
	<!-- 查询简单的项目信息 -->
    <select id="querySimplePrj" parameterType="java.util.Map" resultMap="simplePrjMap">  
        select prj_Id,prj_Name from t_project where prj_id=#{id}
    </select> 

	<!-- 查询所有的简单项目信息 -->
    <select id="selectSimples" resultMap="simplePrjMap">  
        select prj_Id,prj_Name from t_project where 1=1 and is_del=1
    </select> 
    
	<!-- 查询简单的用户 -->
    <select id="querySimpleUser" parameterType="java.util.Map" resultMap="simpleUserMap">  
        select user_id,user_name from t_user where user_id=#{id}
    </select> 

    <!-- 查询记录  数 -->
    <select id="selectAllCnt" resultType="int">  
        select count(*) from t_project ORDER BY prj_id DESC
    </select> 
    
    <!-- 插入新的记录基本信息 -->
    <insert id="insert" parameterType="Project">  
    	<selectKey order="BEFORE" keyProperty="prjId" resultType="string">
			select
			'ST'||t_project_seq.nextval from dual
		</selectKey>
        insert into t_project(prj_Id,prj_Name,prj_Background,prj_introduce,is_Del,parent_prj,create_user)
         values(#{prjId},#{prjName},#{prjBackground},#{prjIncloduce},#{isDel},#{parentPrj.prjId,jdbcType=VARCHAR},#{createUser.userId,jdbcType=VARCHAR})  
    </insert> 
    
    <!-- 更新旧的记录基本信息 -->
    <update id="update" parameterType="Project">
        update t_project set prj_Name=#{prjName,jdbcType=VARCHAR},
	        prj_Background=#{prjBackground,jdbcType=VARCHAR},
	        prj_introduce=#{prjIncloduce,jdbcType=VARCHAR},
	        is_Del=#{isDel,jdbcType=NUMERIC},
	        parent_prj=#{parentPrj.prjId,jdbcType=VARCHAR},
	        update_user=#{updateUser.userId,jdbcType=VARCHAR}
	      where prj_Id=#{prjId}
    </update>
    
    <!-- 根据id删除单条记录 -->
    <update id="deleteById" parameterType="java.lang.String">
    	update t_project set is_del=0 where prj_id=#{prjId}
    </update>

    <!-- 修改当前版本号 -->
    <update id="addVersion" parameterType="Project">
    	update t_project set prj_version=#{currentVersion.versionId,jdbcType=VARCHAR} where prj_id=#{prjId}
    </update>
    
    <!-- 查询所有记录数 -->
    <select id="selectAll" resultMap="prjMap">
		<![CDATA[
        select prj_Id,
			prj_Name,
			prj_Background,
			prj_introduce,
			create_time,
			update_time,
			create_user,
			update_user,
			parent_prj,
			prj_version
		FROM t_project where is_del=1 ORDER BY prj_id DESC
	    ]]>
    </select>
 
</mapper>
    这里要讲解一下的是resultMap节点里面的association节点,与他类似的还有connection节点,他们用于作一对一、一对多、多对多时对象里面的特殊属性。节点中property属性对应对象中的对象变量。column对应外键,select属性映射下面的一个查询,查询该对象变量的数据。至此,springMVC+mybatis的配置完毕。下面编写Daosupport就基本大功告成。

Daosupport.java

package ffcs.team.mgr.dao.support;

import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.util.Assert;

import ffcs.team.mgr.entity.BaseEntity;

/**
 * DAO基本操作封装
 * */
public class DaoSupport<T extends BaseEntity> extends SqlSessionDaoSupport {
    private Class<T> entityClass;
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public DaoSupport() {
        Type genType = getClass().getGenericSuperclass();
        Type[] param = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) param[0];
    }

    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    @Resource
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        super.setSqlSessionTemplate(sqlSessionTemplate);
    }

    private String getDefaultNamespace() {
        return entityClass.getCanonicalName() + '.';
    }

}
    具体的dao根据return this.getSqlSession().selectOne("mapper里面select的id",obj);(obj:sql语句用到的参数parameterType)等方法进行数据库操作。


demo下载



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值