目录

Spring-SpringMVC-JPA整合案例

三种整合方式

1)LocalEntityManagerFactoryBean:

适用于那些仅使用 JPA 进行数据访问的项目,该 FactoryBean 将根据JPA PersistenceProvider 自动检测配置文件进行工作,一般从“META-INF/persistence.xml”读取配置信息,这种方式最简单,但不能设置 Spring 中定义的DataSource,且不支持 Spring 管理的全局事务。

2)从JNDI中获取:

用于从 Java EE 服务器获取指定的EntityManagerFactory,这种方式在进行 Spring 事务管理时一般要使用 JTA 事务管理

3)LocalContainerEntityManagerFactoryBean:

适用于所有环境的 FactoryBean,能全面控制 EntityManagerFactory 配置,如指定 Spring 定义的 DataSource 等等。

Spring整合JPA步骤

1.导入需要使用的包

​ 1)导入Spring以及SpringMVC

​ 2)导入aspect包

​ 3)导入依赖日志包commons-logging-1.2.jar

​ 4)导入HIbernate以及HIbernate对JPA实现包

​ 5)导入eclipselink

​ 6)导入二级缓存包ehcache

​ 7)导入数据库驱动

​ 8)导入c3p0数据连接池

​ 9)导入jstl

2.添加数据库资源文件

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jpa
jdbc.user=root
jdbc.password=root
3.配置Spring配置文件
  • 配置数据库连接
<!-- 引入外部资源文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}" />
    <property name="password" value="${jdbc.password}" />
    <property name="driverClass" value="${jdbc.driver}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <!-- 队列中的最小连接数 -->
    <property name="minPoolSize" value="15"></property>
    <!-- 队列中的最大连接数 -->
    <property name="maxPoolSize" value="25"></property>
    <!-- 当连接耗尽时创建的连接数 -->
    <property name="acquireIncrement" value="15"></property>
    <!-- 等待时间 -->
    <property name="checkoutTimeout" value="10000"></property>
    <!-- 初始化连接数 -->
    <property name="initialPoolSize" value="20"></property>
    <!-- 最大空闲时间,超出时间连接将被丢弃 -->
    <property name="maxIdleTime" value="20"></property>
    <!-- 每隔60秒检测空闲连接 -->
    <property name="idleConnectionTestPeriod" value="60000"></property>
</bean>
  • 配置EntityManagerFactory对象

    <!-- 配置entityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- jpa注解所在的包 -->
        <property name="packagesToScan" value="com.miya.ssp.entities" />
        <!-- 配置jpa提供商的适配器,可以通过内部bean的方式类配置 -->
        <property name="jpaVendorAdapter">
               <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <!-- 配置JPA的基本属性 -->
        <property name="jpaProperties">
            <!-- 配置jpa基本属性 -->
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 配置二级缓存 -->
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">
                org.hibernate.cache.ehcache.EhCacheRegionFactory
                </prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
            </props>
        </property>
    </bean>
  • 事物及其他配置,在这里我们只需要管理非@Controller的bean就行

    <!-- 配置事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <!-- 配置支持注解的事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>
    <!-- 配置自动扫描的包 -->
          <context:component-scan base-package="com.miya.ssp" >
              <!-- 除了@Controller修飾的全部都要 -->
              <context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller"/>
          </context:component-scan>
4.配置SpringMVC配置文件
  • 在这里我们只管理@Controller的bean

    <!-- 扫描所有@Controller注解修饰的类 -->
      <context:component-scan base-package="com.miya.ssp">
          <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    <!--将非mapping配置下的请求交给默认的Servlet来处理 -->
    <mvc:default-servlet-handler />
    <!--如果添加了默认servlet,mvc请求将无效,需要添加annotation-driven -->
    <mvc:annotation-driven></mvc:annotation-driven>
    
    <!-- 配置试图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="WEB-INF/views/"/>
      <property name="suffix" value=".jsp"/>
    </bean>
5.配置WEB.xml文件
<!-- 添加Spring容器的监听 -->
    <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>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <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>
    <!-- 启动SpringMVC核心控制器 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 添加PUT DELETE支持 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

解决JPA懒加载问题

如果我们在属性里设置了懒加载那么,在页面上会报错,Spring给我们提供了一个JPA懒加载解决的方案,我们只需要在WEB.XML中配置,就可以很好的解决JPA在页面上使用到关联对象报出的懒加载错误。

<!-- 解决JPA懒加载问题 -->
    <filter>
      <filter-name>OpenEntityManager</filter-name>
      <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenEntityManager</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
10-05 21:08