版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
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.11</version>
<scope>test</scope>
</dependency>
</dependencies>
1.2 配置
配置文件 applicationContext.xml
集成顺序jdbc.properties->dataSource->entityManagerFactory->事务->dao->service->junit->action
jdbc.properties
<context:property-placeholder location="classpath:jdbc.properties"/>
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>
entityManagerFactory
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 配置属性 setDataSource-->
<property name="dataSource" ref="dataSource"></property>
<!-- 扫描实体类的配置 entity-->
<property name="packagesToScan" value="cn.itsource.ssj.domain"></property>
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 是否显示sql-->
<property name="showSql" value="true"></property>
<!-- 是否创建表-->
<property name="generateDdl" value="true"></property>
<!--数据库方言-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"></property>
</bean>
</property>
</bean>
事务
<!-- 事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!-- 开启事务 扫描@Transaction这种注解-->
<tx:annotation-driven/>
dao层
package cn.itsource.ssj.dao;
import cn.itsource.ssj.domain.Product;
import java.util.List;
public interface IProductDao {
//准备crud
void save(Product product);
void delete(Long id);
void update(Product product);
Product queryOne(Long id);
List<Product> queryAll();
}
dao层实现类
package cn.itsource.ssj.dao.impl;
import cn.itsource.ssj.dao.IProductDao;
import cn.itsource.ssj.domain.Product;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Repository
public class ProductDaoImpl implements IProductDao {
//通过持久化上下文得到entityManager
@PersistenceContext
private EntityManager entityManager;
//新增
public void save(Product product) {
entityManager.persist(product);
}
public void delete(Long id) {
//删除之前先查询
Product product = queryOne(id);
if(product!=null){
entityManager.remove(product);
}
}
//修改
public void update(Product product) {
entityManager.merge(product);
}
//查询
public Product queryOne(Long id) {
return entityManager.find(Product.class, id);
}
//查询所有数据使用jpql语句
public List<Product> queryAll() {
String jpql = "select o from Product o";
Query query = entityManager.createQuery(jpql);
return query.getResultList();
}
}
service层
package cn.itsource.ssj.service;
import cn.itsource.ssj.domain.Product;
import java.util.List;
public interface IProductService {
void save(Product product);
void update(Product product);
void delete(Long id);
Product queryOne(Long id);
List<Product> queryAll();
}
service层实现类
package cn.itsource.ssj.service.impl;
import cn.itsource.ssj.dao.IProductDao;
import cn.itsource.ssj.domain.Product;
import cn.itsource.ssj.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class ProductServiceImpl implements IProductService {
@Autowired
private IProductDao productDao;
@Transactional(propagation = Propagation.REQUIRED)
public void save(Product product) {
productDao.save(product);
}
@Transactional(propagation = Propagation.REQUIRED)
public void update(Product product) {
productDao.update(product);
}
@Transactional(propagation = Propagation.REQUIRED)
public void delete(Long id) {
productDao.delete(id);
}
public Product queryOne(Long id) {
return productDao.queryOne(id);
}
public List<Product> queryAll() {
return productDao.queryAll();
}
}
组件扫描器:可以处理@Repository, @Service @Controller,@Autowired,@PersistenceContext 注解
<context:component-scan base-package="cn.itsource.ssj"></context:component-scan>
junit
@Autowired
IProductService productService;
@Test
@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
2.Spring集成SpringMVC
2.1配置web.xml
监听器读取配置
<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>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
核心控制器
<!-- 核心控制器配置-->
<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
扫描controller
<!-- 扫描controller-->
<context:component-scan base-package="cn.itsource.ssj.web.controller"></context:component-scan>
静态资源放行
<!-- 静态资源放行-->
<mvc:default-servlet-handler/>
扫描RequstMapping
<mvc:annotation-driven/>
视图解析器
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
2.3ProductController
package cn.itsource.ssj.web.controller;
import cn.itsource.ssj.domain.Product;
import cn.itsource.ssj.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
IProductService iProductService;
@RequestMapping("/index")
public String index(){
System.out.println("aaaaaaaaaaaaa");
return "product";
}
@RequestMapping("/list")
@ResponseBody
public List<Product> list(){
return iProductService.queryAll();
}
}
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 type="text/javascript">
//格式化产品类型
function formatterProductType(value){
console.log(value)
if(value != null){
return value.name;
}
}
</script>
</head>
<body>
<table class="easyui-datagrid" title="Basic DataGrid" style="width:700px;height:250px"
data-options="singleSelect:true,collapsible:true,url:'/product/list',method:'get'">
<thead>
<tr>
<th data-options="field:'id',width:80">id</th>
<th data-options="field:'name',width:100">产品名称</th>
<th data-options="field:'dir',width:100,formatter:formatterProductType" >产品类型</th>
</tr>
</thead>
</table>
</body>
</html>
修改web.xml,解决延迟加载的异常
<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;