Spring+MyBatis实践—工程配置

初次实践:Spring+MyBatis技术搭建框架,采用Bootstrap前端开源框架。

简介:

 MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

工程架构图:

  

  

1、工程架包引入:pom.xml

<properties>
        <junit.version>3.8.1</junit.version>
        <spring.version>3.0.7.RELEASE</spring.version>
        <dbcp.version>1.4</dbcp.version>
        <fileupload.version>1.2.2</fileupload.version>
        <commons.io.version>2.4</commons.io.version>
        <jstl.version>1.2</jstl.version>
        <asm.version>3.3</asm.version>
        <aspectj.version>1.7.0</aspectj.version>
        <cglib.version>2.2</cglib.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- spring 配置 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 提供事务支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- aopalliance -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${dbcp.version}</version>
        </dependency>
        <!-- DBCP数据源依赖于commons-pool类包 -->
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.5.6</version>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <!-- Aspectj 支持 ,在aop增强织入时,需要使用org.aspectj.weaver支持 -->
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>${asm.version}</version>
        </dependency>
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
        <!-- 用于创建代理的CGlib包 -->        
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>${cglib.version}</version>
        </dependency>
        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- 打日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>
View Code

 

2.MyBatis配置

mybatisConfig.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> 
        <typeAlias alias="User" type="com.crazysnail.domain.User"/>
        <typeAlias alias="Blog" type="com.crazysnail.domain.Blog"/>
        <typeAlias alias="Comment" type="com.crazysnail.domain.Comment"/>
    </typeAliases>
    <!-- 指定接口的实现映射文件;如果此处未指定,可以在配置SqlSessionFactory时,通过SqlSessionFactory的mapperLocations属性配置 -->
<!--     <mappers> -->
<!--           <mapper resource="com/crazysnail/domain/mybatis/User.xml"/>       -->
<!--     </mappers> -->
</configuration>

 

MyBatis的配置文件中,主要是别名的声明。

3、Spring容器配置:

为了方便Bean的管理,将Spring的配置文件分为了多个,包括spring-main.xml、spring-datasources.xml、spring-service.xml

spring-main.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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <import resource="spring-datasources.xml"/>
    <import resource="spring-service.xml"/>
</beans>

 

spring-main.xml主要负责引入其他的配置文件,进行整合。

spring-datasources.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: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">
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" 
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://127.0.0.1:3306/crazysnailweb?useUnicode=true&amp;characterEncoding=UTF-8" 
        p:username="root"
        p:password="123456" 
        p:maxIdle="10"
        p:minIdle="10" />
    
    <!-- 其中p:mapperLocations指定数据库操作文件的地址 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource"
        p:configLocation="classpath:mybatisConfig.xml"
        p:mapperLocations="classpath:com/crazysnail/domain/mybatisConfig/*.xml" 
        />
    
    <!-- mybatis数据访问的核心模板 -->
    <bean class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>
    
    <!-- 用于将接口映射为具体的实例 ,使得在Service中可以直接注入相关的Dao接口来进行数据访问-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:sqlSessionFactory-ref="sqlSessionFactory"
        p:basePackage="com.crazysnail.dao"
        />
</beans>

 

spring-datasources.xml主要配置数据源和引入MyBatis的核心Bean来支持数据访问。

【注:此处说明一下引入的几个关于mybatis的Bean。

  • SqlSessionFactory:MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。可以从SqlSessionFactory中获取SqlSession,而SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法。可以用 SqlSession 实例来直接执行已映射的 SQL 语句。
  • SqlSessionTemplate:实现了SqlSession接口中的所有执行SQL的方法,需要SqlSessionFactory实例来作为构造参数。
  • MapperScannerConfigurer:该实例的引入,将映射文件中的数据访问语句映射到映射文件命名空间所指定的Dao接口中声明的方法。】

spring-service.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: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/tx
       http://www.springframework.org/schema/tx/spring-tx-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">
    
    <context:component-scan base-package="com.crazysnail.service" />
    
    <!-- 对标注@Transactional注解的Bean进行加工处理,以织入事务管理切面 -->
    <!-- 默认情况下,<tx:annotation-driven的transaction-manager的值为transactionManager,因而此处可直接简化为 <tx:annotation-driven/>-->
    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref = "dataSource"/>
    
    <!-- 对服务层的类提供事务支持 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="serviceMethod" expression="execution(* com.crazysnail.service..*(..))"/>
        <!-- 引用事务增强 -->
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
    </aop:config>
    
    <!-- 事务增强 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--事务属性定义  -->
        <tx:attributes>
            <tx:method name="get*" read-only="false"/>
            <tx:method name="add*" rollback-for="Exception"/>
            <tx:method name="update*"/>
        </tx:attributes>
    </tx:advice>
</beans>

 

spring-service.xml主要配置扫描service层,并且为service层通过aop添加事务增强。

4、web容器配置:

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:spring-main.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 使用Filter进行编码转换 -->
    <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>/*</url-pattern> <!-- 不要使用/,使用/*代替才能够真正起作用,还需要配置在ContextLoaderListener后才能起作用  -->
    </filter-mapping>
    
    <!-- 用户权限控制 -->
    <filter>
        <filter-name>authenFilter</filter-name>
        <filter-class>com.crazysnail.filter.AuthenFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>authenFilter</filter-name>
        <url-pattern>/user/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置DispatcherServlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app> 

 

web.xml文件指定了spring容器配置文件的位置、用于启动Spring容器的监听器(ContextLoaderListener)、用于对用户请求转码的编码转换过滤器和权限验证过滤器及用于请求分发的DispatcherServlet。

5、对于Servlet的配置:

dispatcher-servlet.xml:

<?xml version= "1.0" encoding ="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven/>
      
    <!-- 静态资源映射 -->
    <mvc:resources mapping="/js/**" location="./js/" />
    <mvc:resources mapping="/user/js/**" location="./js/" /><!-- 设置权限的静态资源访问 -->
    <mvc:resources mapping="/css/**" location="./css/" />
    <mvc:resources mapping="/user/css/**" location="./css/" />
    <mvc:resources mapping="/fonts/**" location="./fonts/" />
    <mvc:resources mapping="/user/fonts/**" location="./fonts/" />
    <mvc:resources mapping="/img/**" location="./img/" />
    <mvc:resources mapping="/user/img/**" location="./img/" />
    <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 -->
    <mvc:default-servlet-handler/>
    
    <context:component-scan base-package="com.crazysnail.controller"/>    
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/views/" 
        p:suffix=".jsp" />
        
</beans>

 

servlet配置文件主要指定了URL映射的相关规则,将处理URL的控制器通过扫描controller包放置到Spring容器中,指定了视图解析器,用于将Controller中返回的逻辑视图名映射到具体的jsp文件。

【注:由于在web.xml中配置的servlet对应的servlet-mapping匹配的url为"/",表明每个链接都会由dispatcher进行分发,而在jsp页面中引入的js、css、图片等静态资源无法通过servlet分发来找到对应资源,此时需要配置静态资源映射。这是通过mvc:resources来进行配置的,对应的文件位置可参考工程结构图。】

总结:

MyBatis与Spring的结合点在于配置spring的数据访问时,

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource"
        p:configLocation="classpath:mybatisConfig.xml"
        p:mapperLocations="classpath:com/crazysnail/domain/mybatisConfig/*.xml" 
        />

通过SqlSessionFactory实例的configLocation属性指明了MyBatis的配置文件的位置,通过mapperLocations属性指明了MyBatis映射文件的位置(这也可以在mybatis配置文件mybatisConfig.xml中声明)。

posted @ 2014-08-21 09:08  _crazysnail_  阅读(2709)  评论(4编辑  收藏  举报