1. Spring集成JPA
1.1 导包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
1.2 加载jdbc.properties
添加context、mvc和tx命名空间(mvc和tx后面会使用)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 加载jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
1.3 配置连接池dataSource
<!-- 配置连接池dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
1.4 配置EntityManagerFactory
<!-- 配置entityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 1.注入DataSource -->
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.cctv.domain" />
<!-- 3.配置JPA的实现 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- private boolean showSql = false;是否显示sql语句 -->
<property name="showSql" value="true" />
<!-- 是否建表 -->
<property name="generateDdl" value="true" />
<!-- 配置数据库方言 -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
1.5 开启注解扫描控制器
<!--开启注解扫描控制器-->
<context:component-scan base-package="com.cctv" />
1.6 配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 开启注解事务管理 -->
<tx:annotation-driven />
service层中配置事务注解
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class ProducteDirServiceImpl implements IProductDirService {
@Autowired
private IProductDirDao productDirDao;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void add(ProductDir productDir) {
productDirDao.add(productDir);
}
}
2. Spring集成SpringMVC
2.1 配置web.xml
配置核心控制器,服务器编码,添加处理懒加载问题的过滤器
<!--服务器编码-->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 处理懒加载问题,entityManger过滤器,必须在struts2过滤器之前 -->
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 监听器读取配置-->
<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>
<!-- 核心控制器(分发请求) -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.2 配置applicationContext-mvc.xml
配置SpringMVC静态资源放行、扫描@RequestMapping、视图解析器、上传解析器、拦截器等
<!-- SpringMVC静态资源放行 -->
<mvc:default-servlet-handler />
<!-- SpringMVC开启注解支持,扫描RequestMapping -->
<mvc:annotation-driven/>
<!-- SpringMVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置多媒体解析器 -->
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
<!-- 配置拦截器组 -->
<mvc:interceptors>
<!-- 拦截器 -->
<mvc:interceptor>
<!-- 要拦截的配置 -->
<mvc:mapping path="/system/*" />
<!-- 设置不拦截的配置 -->
<mvc:exclude-mapping path="/login.jsp"/>
<mvc:exclude-mapping path="/login"/>
<!-- 配置拦截器,定义一个类,实现HandlerInterceptor,在preHandle方法中设置拦截条件 -->
<bean class="com.cctv.interceptor.LoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
登录拦截器类
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private UserServiceImpl userServiceImpl;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
User user = (User) req.getSession().getAttribute("user");
if(user==null){
resp.sendRedirect("/login.jsp");
return false;
}
return true;
}
}
3. 解决延迟加载的异常(LazyInitializationException)
关联映射关系中设置了fetch=FetchType.LAZY 懒加载,数据返回给页面层的时候,此时Session已经关闭,导致延迟加载的数据访问异常,需要在web.xml中配置过滤器(参考2.1)
在domain配置了懒加载的实体类中添加@JsonIgnoreProperties({“hibernateLazyInitializer”, “handler”})注解
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="dir_id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private ProductDir productDir;