1. 三大框架整合
ssj: springmvc+spring+jpa
2. SSJ(整合)
spring项目管理专家,所有的bean都可以交给spring管理
(1)先整合 spring和jpa
(2)在整合 spring和springmvc
a)导包
b)配置 web.xml和applicationContext-mvc.xml里面配置
3.Spring集成JPA
Spring4 + SpringMVC+ jpa/hibernate4
建议:先完成Spring与jpa的集成
<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.11</version>
<scope>test</scope>
</dependency>
</dependencies>
写一个domain对象,配置JPA映射
@Entity
@Table(name = "t_product")
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
Bean对象注入的顺序
jdbc.properties->dataSource->entityManagerFactory->dao->service->junit->action
加载jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssj
jdbc.username=root
jdbc.password=root
<?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"
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">
<!-- 加载jdbc.properties -->
<context:property-placeholder location="jdbc.properties" />
配置连接池dataSource
<!-- 配置连接池dataSource -->
<!-- destroy-method="close当前bean销毁的时候,会先调用close方法,关闭连接" -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- 依赖注入连接池需要的属性 -->
<!-- property name="是BasicDataSource的set方法,本质属性" -->
<!-- property value="是jdbc.properties配置文件的key" -->
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
配置entityManagerFactory
<!-- org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter引入默认entityManagerFactory名称 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 1.注入DataSource -->
<property name="dataSource" ref="dataSource" />
<!-- 2.从哪个包去扫描@Entity,domain包 -->
<!-- public void setPackagesToScan(String... packagesToScan) { -->
<property name="packagesToScan" value="cn.itsource.ssj.domain" />
<!-- 3.配置JPA的实现 -->
<!-- private JpaVendorAdapter jpaVendorAdapter; setJpaVendorAdapter() private OtherBean otherBean -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter -->
<!-- private boolean showSql = false;是否显示sql语句 -->
<property name="showSql" value="true" />
<!-- private boolean generateDdl = false;是否建表 数据定义语言 -->
<property name="generateDdl" value="true" />
<!-- private String databasePlatform;原来方言 -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
IProductDao
public interface IProductDao {
void save(Product product);
void update(Product product);
void delete(Long id);
Product get(Long id);
List<Product> getAll();
}
ProductDaoImpl
@Repository
public class ProductDaoImpl implements IProductDao {
// @Autowired 不能使用这个注入
@PersistenceContext // 持久层上下文管理器
private EntityManager entityManager;
@Override
public void save(Product product) {
entityManager.persist(product);
}
@Override
public void update(Product product) {
entityManager.merge(product);
}
@Override
public void delete(Long id) {
Product product = get(id);
if (product != null) {
entityManager.remove(product);
}
}
@Override
public Product get(Long id) {
return entityManager.find(Product.class, id);
}
@Override
public List<Product> getAll() {
String jpql = "select o from Product o";
return entityManager.createQuery(jpql).getResultList();
}
}
组件扫描
<!-- 扫描dao、service、action组件 -->
<!-- 可以处理@Repository, @Service, and @Controller,@Autowired,@PersistenceContext 注解-->
<context:component-scan base-package="cn.itsource.ssj" />
IProductService
public interface IProductService {
void save(Product product);
void update(Product product);
void delete(Long id);
Product get(Long id);
List<Product> getAll();
}
ProductServiceImpl
@Service
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductDao productDao;
@Override
public void save(Product product) {
productDao.save(product);
}
@Override
public void update(Product product) {
productDao.update(product);
}
@Override
public void delete(Long id) {
productDao.delete(id);
}
@Override
public Product get(Long id) {
return productDao.get(id);
}
@Override
public List<Product> getAll() {
return productDao.getAll();
}
}
声明式事务管理(注解版本)
在spring的配置文件添加一点事务配置,并且在service层类上面添加一些注解,就可以实现事务管理
添加一个tx命名空间
<?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:tx="http://www.springframework.org/schema/tx"
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">
添加事务配置
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 开启注解事务管理 ,解析@Transactional注解 -->
<!-- transaction-manager="transactionManager"默认找bean.id=transactionManager事务管理器 -->
<tx:annotation-driven />
ProductServiceImpl
@Service
// 默认事务配置
// @Transactional
// 上面配置等价于下面配置
@Transactional(propagation = Propagation.REQUIRED)
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductDao productDao;
@Override
public void save(Product product) {
productDao.save(product);
}
@Override
public void update(Product product) {
productDao.update(product);
}
@Override
public void delete(Long id) {
productDao.delete(id);
}
@Override
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public Product get(Long id) {
return productDao.get(id);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Product> getAll() {
return productDao.getAll();
}
}
Junit
@Autowired
IProductService productService;
@Test
public void save() throws Exception {
System.out.println("代理类:" + productService.getClass());
Product product = new Product();
product.setName("苹果的弟弟");
productService.save(product);
}
代理类:class com.sun.proxy.$Proxy23
4.Spring集成SpringMVC
- 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<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>
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</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>
</web-app> - 配置applicationContext.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: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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="cn.itsource.ssj.controller" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!--<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
<!--<property name="maxUploadSize">-->
<!--<value>${1024*1024*10}</value>-->
<!--</property>-->
<!--</bean>-->
</beans> - ProductController
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private IProductService productService;
@RequestMapping("/index")
public String index(){
return "product";
}
@RequestMapping("/list")
@ResponseBody
public List<Product> list(){
return productService.getAll();
}
@RequestMapping("/delete")
@ResponseBody
public Map delete(Long id){
productService.delete(id);
Map<String,Object> map = new HashMap<>();
map.put("success", true);
return map;
}
@RequestMapping("/save")
@ResponseBody
public Map save(Product product){
if(product.getId()!=null){
productService.update(product);
}else{
productService.save(product);
}
Map<String,Object> map = new HashMap<>();
map.put("success", true);
return map;
}
} - 配置好,启动tomcat,抛出一下异常
- 在web.xml添加一个监听器,来实例化spring容器
<!-- 添加一个监听器,来实例化spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 再次启动tomcat,又抛出异常
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more
默认会去WEB-INF下面找配置文件,而此路径没有
- 在web.xml添加一个上下文的初始化参数,来告诉spring从哪里加载配置文件
<!-- 添加一个上下文的初始化参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 怎样快速找contextConfigLocation名字
找监听器ContextLoaderListener的父类ContextLoader
有一个常量配置
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
9.不能加载jdbc.properties异常
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/jdbc.properties]
10.
修改spring的配置文件
<!-- 加载jdbc.properties -->
<!-- 跑web必须在前面添加classpath:前缀 -->
<context:property-placeholder location="classpath:jdbc.properties" />
访问http://localhost/product/index,出现404异常,
因为没有写jsp页面,此jsp页面和原来写JPA集成SpringMVC的jsp是一致的
product.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/easyui/themes/icon.css">
<script type="text/javascript" src="/easyui/jquery.min.js"></script>
<script type="text/javascript" src="/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/easyui/locale/easyui-lang-zh_CN.js"></script>
<script>
function objFormat(o,r) {
if(o)return o.name;
}
…
</script>
</head>
<body>
<table id="productGrid" class="easyui-datagrid" style="width:400px;height:250px"
data-options="url:'/product/list',fitColumns:true,singleSelect:true,fit:true,toolbar:'#tt'">
<thead>
<tr>
<th data-options="field:'id',width:100">编码</th>
<th data-options="field:'name',width:100">名称</th>
<th data-options="field:'productDir',width:100,align:'right',formatter:objFormat">产品</th>
</tr>
</thead>
<div id="tt">
<a href="javascript:;" class="easyui-linkbutton" data-method="save">添加</a>
<a href="javascript:;" class="easyui-linkbutton" data-method="update" >修改</a>
<a href="javascript:;" class="easyui-linkbutton" data-method="delete">删除</a>
</div>
</table>
</body>
</html>
5.以同样的方式添加产品类型
- 添加产品类型模型
模型ProductDir,修改Product添加@ManyToOne
写dao,service
2.修改web.xml,解决延迟加载的异常
<!-- 添加关闭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>
配置:
在Product类里面配置
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="dir_id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private ProductDir productDir;