Mybatis3+Spring4+SpringMVC4 整合

来源:互联网 发布:人工智能治理政策 编辑:程序博客网 时间:2024/05/17 03:02

1.新建mavenWeb项目

maven依赖jar包

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>spring</groupId>  <artifactId>mvc</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>war</packaging>  <dependencies>  <dependency>  <groupId>com.hundsun.jresplus</groupId>  <artifactId>jresplus-mvc</artifactId>  <version>1.0.7</version>  </dependency>  <!-- <dependency>  <groupId>org.slf4j</groupId>  <artifactId>log4j-over-slf4j</artifactId>  <version>1.7.2</version>  </dependency>    <dependency>  <groupId>com.hundsun.jresplus</groupId>  <artifactId>jresplus-ui-runtime</artifactId>  <version>1.0.26-SNAPSHOT</version>  </dependency>  <dependency>  <groupId>com.hundsun.jresplus</groupId>  <artifactId>jresplus-ui-web</artifactId>  <version>1.0.26-SNAPSHOT</version>  <classifier>nolib</classifier><type>war</type>  </dependency> -->  <dependency>  <groupId>org.slf4j</groupId>  <artifactId>slf4j-log4j12</artifactId>  <version>1.7.5</version>  </dependency>  <dependency>  <groupId>com.hundsun.jresplus</groupId>  <artifactId>jresplus-dao-mybatis3</artifactId>     <version>1.0.1</version>  </dependency>  <dependency>  <groupId>c3p0</groupId>  <artifactId>c3p0</artifactId>     <version>0.9.1.2</version>  </dependency>  <dependency>    <groupId>org.hibernate</groupId>    <artifactId>hibernate-validator</artifactId>    <version>4.3.0.Final</version></dependency>  <dependency>    <groupId>org.aspectj</groupId>    <artifactId>aspectjweaver</artifactId>    <version>1.8.9</version></dependency>  </dependencies></project>

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/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4"><display-name>jresplusMvcDemo</display-name><!-- spring bean 资源路径 --><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/conf/spring/service-beans.xml</param-value></context-param><!-- jresplus-mvc配置文件位置 --><context-param><param-name>JresConfigLocation</param-name><param-value>/WEB-INF/conf/server.properties</param-value></context-param><!-- <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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>*.htm</url-pattern></filter-mapping><filter><filter-name>liulongFilter</filter-name><filter-class>com.hundsun.jresplus.mvc.demo.filter.liulongFilter</filter-class><init-param><param-name>classProp</param-name><param-value>内置属性</param-value></init-param><init-param><param-name>filterConfig</param-name><param-value>filterConfig属性</param-value></init-param></filter><filter-mapping><filter-name>liulongFilter</filter-name><url-pattern>*.htm</url-pattern></filter-mapping> --><!-- 由spring载入的log4j配置文件位置 --><!-- <context-param><param-name>log4jConfigLocation</param-name><param-value>/WEB-INF/conf/log4j.properties</param-value></context-param> --><!-- 设置为true或不设置,会将webAppRootKey的值写入系统参数中(System.setProperty) --><!-- <context-param><param-name>log4jExposeWebAppRoot</param-name><param-value>true</param-value></context-param> --><!-- spring默认刷新log4j配置文件的间隔,单位为ms --><!-- <context-param><param-name>log4jRefreshInterval</param-name><param-value>10000</param-value></context-param> --><!-- 不配置时为webapp.root,当两个使用logj的web应用放在一个tomcat中时最好配置为不同名 --><!-- <context-param><param-name>webAppRootKey</param-name><param-value>jres.root</param-value></context-param> --><!--此过滤器已经包含字符编码、contain、nosession(nosession支持开关) --><!-- <filter><filter-name>jresFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param><param-name>targetBeanName</param-name><param-value>jresFilter</param-value></init-param></filter><filter><filter-name>hornFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param><param-name>targetBeanName</param-name><param-value>hornFilter</param-value></init-param></filter><filter-mapping><filter-name>jresFilter</filter-name><url-pattern>*.htm</url-pattern></filter-mapping><filter-mapping><filter-name>jresFilter</filter-name><url-pattern>*.json</url-pattern></filter-mapping><filter-mapping><filter-name>jresFilter</filter-name><url-pattern>*.xml</url-pattern></filter-mapping><filter-mapping><filter-name>hornFilter</filter-name><url-pattern>*.htm</url-pattern></filter-mapping> --><!-- spring 加载log4j的监听器 --><!-- <listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener> --><!-- jresplus-mvc 上下文加载监听器,代替spring的上下文监听器 --><listener><listener-class>com.hundsun.jresplus.web.context.ContextLoaderListener</listener-class></listener><!-- <listener><listener-class>com.hundsun.jresplus.mvc.demo.listener.liulongListener</listener-class></listener> --><!-- 避免由于使用introspector方式引起的泄漏,使用此监听器可以再关闭web应用时释放 --><!-- <listener><listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class></listener> --><!-- jresplus-mvc的主控制器代替spring原生的DispatcherServlet --><servlet><servlet-name>jresServlet</servlet-name><servlet-class>com.hundsun.jresplus.web.servlet.DispatcherServlet</servlet-class><load-on-startup>2</load-on-startup></servlet><servlet-mapping><servlet-name>jresServlet</servlet-name><url-pattern>*.htm</url-pattern></servlet-mapping><servlet-mapping><servlet-name>jresServlet</servlet-name><url-pattern>*.json</url-pattern></servlet-mapping><servlet-mapping><servlet-name>jresServlet</servlet-name><url-pattern>*.xml</url-pattern></servlet-mapping><!-- <servlet><servlet-name>liulongServlet</servlet-name><servlet-class>com.hundsun.jresplus.mvc.demo.servlet.LiulongServlet</servlet-class><load-on-startup>3</load-on-startup></servlet><servlet-mapping><servlet-name>liulongServlet</servlet-name><url-pattern>*.htm</url-pattern></servlet-mapping> --><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>

3.创建数据库DEMO_EMPLOYEE

create table DEMO_EMPLOYEE (   ID                   NUMBER(18)           not null,   NAME            VARCHAR2(50),   AGE                  NUMBER(8),);

4.创建实体类和dao接口文件


5.DemoEmployee.java

public class DemoEmployee {private static final long serialVersionUID = -5170451212256831591L;private Long id;private String name;private Integer age;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}

IDemoEmployeeDAO.java

public interface IDemoEmployeeDAO {public abstract Object getById(Serializable serializable);    public abstract void save(Object obj);    public abstract void update(Object obj);    public abstract void deleteById(Serializable serializable);}

IDemoEmployeeDAO.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.hundsun.jresplus.mvc.demo.module.dao.IDemoEmployeeDAO" >  <resultMap id="BaseResultMap" type="com.hundsun.jresplus.mvc.demo.entity.DemoEmployee" >   <id column="ID" property="id" jdbcType="NUMERIC" />    <result column="NAME" property="name" jdbcType="VARCHAR" />    <result column="AGE" property="age" jdbcType="NUMERIC" />   </resultMap>   <parameterMap id="BaseResultMap" type="com.hundsun.jresplus.mvc.demo.dto.EmployeeQry" >   </parameterMap>   <!-- 基本的查询结果字段 sql片断--><sql id="Base_Column_List" >    t.ID, t.NAME, t.AGE</sql><!-- 基本的查询条件sql片断--><sql id="Base_Column_Cond" >  <if test="deptId != null" >            and t.DETP_ID = #{deptId}    </if>  <if test="likeName != null" >       <bind name="v_likeName" value=""%" + _parameter.getLikeName() + "%"" />          and t.NAME like #{v_likeName}    </if>    <if test="maxAge != null" >    <![CDATA[ and t.AGE <= #{maxAge}  ]]>          </if>    <if test="minAge != null" >    <![CDATA[ and t.AGE >= #{minAge}  ]]>    </if>  </sql>         <insert id="save" parameterType="com.hundsun.jresplus.mvc.demo.entity.DemoEmployee" >    insert into DEMO_EMPLOYEE (ID, NAME, AGE)    values (#{id,jdbcType=NUMERIC}, #{name}, #{age})  </insert>    <update id="update" parameterType="com.hundsun.jresplus.mvc.demo.entity.DemoEmployee" >    update DEMO_EMPLOYEE    <set>      <if test="name != null" >        NAME = #{name},      </if>      <if test="age != null" >        AGE = #{age},      </if>      <if test="version != null" >        VERSION = VERSION+1,      </if>   </set>    where ID = #{id}    <if test="version != null" >        and VERSION = #{version}     </if>  </update>    <delete id="deleteById" parameterType="java.lang.Long" >    delete from DEMO_EMPLOYEE    where ID = #{id}  </delete>    <select id="getById" resultMap="BaseResultMap" parameterType="java.lang.Long" >    select <include refid="Base_Column_List" />    from DEMO_EMPLOYEE t    where t.ID = #{id}  </select>    <select id="queryWithPage" resultType="com.hundsun.jresplus.mvc.demo.entity.DemoEmployee" parameterType="com.hundsun.jresplus.mvc.demo.dto.EmployeeQry">    select <include refid="Base_Column_List" />, d.NAME AS DEPT_NAME    from DEMO_EMPLOYEE t, DEMO_DEPARTMENT d where t.dept_id=d.id    <include refid="Base_Column_Cond" />  </select>             </mapper>

6.spring配置文件


7.service-beans.xml

<?xml version="1.0" encoding="GB2312"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">        <context:component-scan base-package="com.hundsun.jresplus"/><context:annotation-config /><bean id="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><property name="basenames"><list><value>i18n/validate</value></list></property><property name="defaultEncoding" value="UTF-8" /><property name="cacheSeconds" value="5"/><property name="useCodeAsDefaultMessage" value="false"/></bean> <bean id="springFactoryUtil"class="com.hundsun.jresplus.mvc.demo.util.SpringFactoryUtil"></bean> <import resource="dao-beans.xml" /></beans>

8.mybatis配置文件dao-beans.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:context="http://www.springframework.org/schema/context"  xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:tx="http://www.springframework.org/schema/tx"  xsi:schemaLocation="http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-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/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数据源 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >        <property name="jdbcUrl" value="${jdbc.url}" />        <property name="driverClass" value="${jdbc.driverClassName}" />        <property name="user" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />        <!--连接池中保留的最大连接数。Default: 15 -->        <property name="maxPoolSize" value="100" />        <!--连接池中保留的最小连接数。-->        <property name="minPoolSize" value="1" />        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->        <property name="initialPoolSize" value="10" />        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->        <property name="maxIdleTime" value="30" />        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->        <property name="acquireIncrement" value="5" />        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements          属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。          如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->        <property name="maxStatements" value="0" />                 <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->        <property name="idleConnectionTestPeriod" value="60" />                 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->        <property name="acquireRetryAttempts" value="30" />                <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效          保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试          获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->        <property name="breakAfterAcquireFailure" value="true" />                 <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的          时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable          等方法来提升连接测试的性能。Default: false -->        <property name="testConnectionOnCheckout"  value="false" />            </bean>        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource" />       <property name="configLocation" value="classpath:mybatis-config.xml"></property>   </bean>   <bean id="demoEmployeeDAO" class="org.mybatis.spring.mapper.MapperFactoryBean">       <property name="mapperInterface" value="com.hundsun.jresplus.mvc.demo.module.dao.IDemoEmployeeDAO"></property>       <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>   </bean> <!-- 分页处理 --><!-- <bean id="paginationInterceptor" class="com.hundsun.jresplus.dao.mybatis3.interceptor.PaginationInterceptor"><property name="pageMapper" value=".*ListPage.*"/></bean> --><!-- 主键生成策略 --><!-- <bean id="dbidGenerator" class="com.hundsun.jresplus.dao.common.id.internal.MemoryDbidGenerator"></bean> --><!-- 主键生成 --><!-- <bean id="idGenInterceptor" class="com.hundsun.jresplus.dao.mybatis3.interceptor.IdGenInterceptor"><property name="dbidGenerator" ref="dbidGenerator"/></bean> --><!-- 乐观锁 --><!-- <bean id="optimisticLockInterceptor" class="com.hundsun.jresplus.dao.mybatis3.interceptor.OptimisticLockInterceptor"></bean> --><!-- oracle数据库 --><!-- <bean id="oracleDialect" class="com.hundsun.jresplus.dao.mybatis3.dialect.OracleDialect"></bean> --><!-- mybatis session factory --><!-- <bean id="sqlSessionFactory" class="com.hundsun.jresplus.dao.mybatis3.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="dataBaseDialect" ref="oracleDialect" /><property name="plugins"><list><ref bean="paginationInterceptor"/><ref bean="idGenInterceptor"/><ref bean="optimisticLockInterceptor"/></list>        </property></bean>     --> <!--mapper 扫描配置  --><!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />basePackage指定要扫描的包,在此包之下的映射器都会被 搜索到。可指定多个包,包与包之间用逗号或分号分隔<property name="basePackage" value="com.hundsun.jresplus.mvc.demo.**.dao" /></bean> --><!-- 事务配置 --><!-- <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/><tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception" /><tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" /><tx:method name="find*" propagation="SUPPORTS" /><tx:method name="get*" propagation="SUPPORTS" /><tx:method name="select*" propagation="SUPPORTS" /></tx:attributes></tx:advice><aop:config><aop:pointcut id="serviceTx"expression="execution(public * com.hundsun..service.*.*(..))" /><aop:advisor pointcut-ref="serviceTx" advice-ref="txAdvice" /></aop:config> --></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>      <mappers>          <mapper resource="com/hundsun/jresplus/mvc/demo/module/dao/IDemoEmployeeDAO.xml"/>      </mappers>  </configuration>

9.测试:

@RequestMapping("/test/test.htm")public void test() {System.out.println("test.......");demoEmployeeDAO=SpringFactoryUtil.getBean("demoEmployeeDAO");DemoEmployee demoEmployee=demoEmployeeDAO.getById(1L);System.out.println(demoEmployee.getName());}

二、另一种配置方式

1.dao-beans.xml

    <!-- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">       <property name="dataSource" ref="dataSource" />       <property name="configLocation" value="classpath:mybatis-config.xml"></property>   </bean>  -->  <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <!-- 自动扫描mapping.xml文件 -->          <property name="mapperLocations" value="classpath:com/hundsun/jresplus/mvc/demo/module/dao/*.xml"></property>      </bean> <!--  <bean id="demoEmployeeDAO" class="org.mybatis.spring.mapper.MapperFactoryBean">       <property name="mapperInterface" value="com.hundsun.jresplus.mvc.demo.module.dao.IDemoEmployeeDAO"></property>       <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>   </bean>  --> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.hundsun.jresplus.mvc.demo.**.dao" />          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>      </bean>  

2.TestAction.java

@Controllerpublic class TestAction {@Autowiredprivate IDemoEmployeeDAO demoEmployeeDAO;@RequestMapping("/test/test.htm")public void test() {System.out.println("test.......");//demoEmployeeDAO=SpringFactoryUtil.getBean("demoEmployeeDAO");DemoEmployee demoEmployee=demoEmployeeDAO.getById(1L);System.out.println(demoEmployee.getName());}}




0 0
原创粉丝点击