文章目录
SSJ集成
什么是三大框架
- ssh Struts2 Spring Hibernate
- ssm SpringMVC Spring MyBatis
- ssj
Struts2 Spring JPA
SpringMVC Spring JPA(这里学习)
SpringMVC Spring Data JPA
maven下载sss所需要包的配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.hibernate.version>4.3.8.Final</org.hibernate.version>
<spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
<com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
<org.slf4j.version>1.6.1</org.slf4j.version>
</properties>
<dependencies>
<!-- Spring的支持包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring上下文包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<!-- 引入web前端的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- SpringMCV上传需要用到io包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 文件上传用到的包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- SpringMVC的json支持包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson.version}</version>
</dependency>
<!-- hibernate的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<!-- SpringData的支持包 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- SpringData的扩展包 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有的依賴都去掉,(害怕下载的spring-data-jpa版本不一致 )-->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--连接池-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--lang包的工具包,apache扩展-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- 測試包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
<scope>provided</scope>
</dependency>
<!-- 日志文件 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!-- 代码生成器模版技术 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6</version>
</dependency>
<!-- shiro的支持包 (权限框架)-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.4.0</version>
<type>pom</type>
</dependency>
<!-- shiro与Spring的集成包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- poi支持的jar包(操作办公软件) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<!-- 图片压缩功能 -->
<!-- 缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.6</version>
</dependency>
<!-- 定时运行 -->
<dependency>
<groupId>quartz</groupId>
<artifactId>quartz</artifactId>
<version>1.5.2</version>
</dependency>
<!-- 邮件支持 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>aisell</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.15.v20140411</version>
<configuration>
<stopPort>9966</stopPort>
<stopKey>foo</stopKey>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
</configuration>
</plugin>
</plugins>
</build>
加载jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///aisell?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=520tlz
配置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:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!--精准扫描-->
<context:component-scan base-package="com.liangze.aisell.service"/>
<!--配置db资源文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<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>
<!--配置entitymanagerfactroy 快捷键alt+insert-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--jpa扫描-->
<property name="packagesToScan" value="com.liangze.aisell.domain"/>
<!--配置jpa-->
<property name="jpaVendorAdapter">
<!--jap规范,jap使用的是hibernate-->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--jpa方言-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!--建表策略,,是否建表-->
<property name="generateDdl" value="false"/>
<!--是否显示sql语句-->
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<!--配置aop的配置事务管理器 1、设置头tx 2、alt+insert jpa-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 开启tx 上面id固定,如果不固定,必须对其进行声明transaction-manager="transactionManager"-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--spring data jpa 配置扫描-->
<jpa:repositories base-package="com.liangze.aisell.repository"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"
<!--Spring Data Jpa扩展BaseRepositoryFactoryBean-->
factory-class="com.liangze.aisell.repository.BaseRepositoryFactoryBean"
/>
</beans>
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--启动spring listener监听器...同Tomcat一起开启-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring的资源文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--核心控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springmvc核心资源文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<!--servlet随着Tomcat一起创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--请求参数符合RESTful风格-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决中文乱码-->
<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>
<!-- 加上OpenEntityManager 解决nosession-->
<filter>
<filter-name>openEntity</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
配置applicationContext-mvc.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
">
<!--扫描controller-->
<context:component-scan base-package="com.liangze.aisell.web.controller"/>
<!--支持springMVC注解-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
<!-- No serializer:配置 objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 -->
<property name="objectMapper">
<bean class="com.liangze.aisell.common.CustomMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--静态资源放行-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<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">
<!-- 设置上传文件的最大尺寸为1MB -->
<property name="maxUploadSize">
<value>1048576</value>
</property>
</bean>
</beans>
创建Controller与页面
- @Controller
控制器类上必加,springmvc才能扫描到 - @RequestMapping("/employee") 网页请求映射url
- @ResponseBody 返回不经过视图解析器
框架SpringDataJpa
- 前面已经导全了包,配置里面也框架SpringDataJpa的配置,这里主要讲解一下
datajpa-1.1配置applicationContext.xml文件
在ssj基础上配置:
<!-- Spring Data Jpa配置 ********************************************-->
<!-- base-package:扫描的包 -->
<jpa:repositories base-package="cn.itsource.pss.repository" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
在ssj基础上配置头上增加:
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
datajpa-1.2完成Repository的功能
- domain父类
抽取共同的如id但是父类必须加注解@MappedSuperclass
Repository增删改查
//获取所有数据
@Test
public void testFindAll() throws Exception{
List<Employee> emps = employeeRepository.findAll();
for (Employee emp :emps){
System.out.println(emp);
}
}
//根据id到一条数据
@Test
public void testFindOne() throws Exception{
Employee employee = employeeRepository.findOne(1L);
System.out.println(employee);
}
//添加与修改都使用save(主要看对象有没有id)
@Test
public void testSave() throws Exception{
Employee employee = new Employee();
//employee.setId(103L);
employee.setUsername("张三");
employee.setPassword("1234");
employee.setEmail("zhangsha@163.com");
employeeRepository.save(employee);
}
//删除数据
@Test
public void testDelete() throws Exception{
employeeRepository.delete(103L);
}
datajpa-1.3分页和排序
排序DESC降序ASC升序
Sort sort = new Sort(Sort.Direction.DESC,"username");
分页加排序,不加sort不排序
Pageable pageable = new PageRequest(0, 10,sort);
employeeRepository.findall(pageable)
respository需要再去继承一个JpaSpecificationExecutor
//高级查询和分页原始的利用Specification
//root获取字段,,criteriaBuilder高级查询功能
@Test
public void testGao() throws Exception{
//按照年龄降序
Sort sort = new Sort(Sort.Direction.DESC,"age");
//分页
Pageable pageable = new PageRequest(0,10,sort);
Page<Employee> page = repository.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Path usernamepath = root.get("username");
Path emailpath = root.get("email");
//模糊查询
Predicate predicate = criteriaBuilder.like(usernamepath, "%1%");
Predicate predicate2 = criteriaBuilder.like(emailpath, "%1%");
//and且
Predicate p = criteriaBuilder.and(predicate, predicate2);
return p;
}
}, pageable);
page.forEach(e-> System.out.println(e));
}
datajpa-1.4:jpa-spec插件
导包
- 前面也直接导了
<!-- jpa的SpecificationSpecification功能封装 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有依赖都过滤 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
代码
//SpringData jpa的扩展包 com.github.wenhao jpa-spec
//Specifications方法 得到类型Specification
@Test
public void testSpec() throws Exception{
//使用jpa-spec工具使用高级查询获取Specification对象
Specification<Employee> specification = Specifications.<Employee>and()
.like("username", "%1%")//模糊查询
.like("email","%1%")
.ge("age", 20)//大于等于18
.build();
//排序
Sort sort = new Sort(Sort.Direction.DESC,"age");
//分页
Pageable pageable = new PageRequest(0,10,sort);
Page<Employee> page = repository.findAll(specification, pageable);
page.forEach(e-> System.out.println(e));
}
datajpa-1.5:Query查询条件
咱们每一个项目是做过高级查询与分页的,大家应该都清楚,查询的数据是从前端由客户输入(或者选择)传到后台的。那么,我们需要注意的情况有哪些呢?
1 用户传的数据有0-n个(我们需要去判断)
2 咱们必需要准备一个对象接收用户传过来的数据(使用Query对象)
3 分页的条件对我们来说也是封装到Query对象中的
BaseQuery:公共的分页条件
public abstract class BaseQuery {
//筛选内容
private String orderByName;
//升降排序ture-DESC(升) false-ASE(降)
private Boolean orderBySort;
//第几页默认等于1
private int currentPage=1;
//一页显示几个 默认10条
private int pageSize=10;
//抽象方法高级查询
public abstract Specification createspec();
//排序
public Sort createSort(){
if (orderByName!=null) {
Sort sort = new Sort(orderBySort ? Sort.Direction.ASC : Sort.Direction.DESC, orderByName);
return sort;
}
return null;
}
//单独取一个方法,页数0就是第一页,对其进行减一
public int getPage() {
return currentPage-1;
}
//更新页数和一页显示条数 加两个set,名字不一致
getset……………………
}
子类domain
子类的一些特有的一些条件,自己先继承父类,
再去实现自己的如:EmployeeQuery:Employee
public class EmployeeQuery extends BaseQuery {
//使用jpa-spec工具使用高级查询获取Specification对象
public Specification createspec() {
Specification<Employee> specification = Specifications.<Employee>and()
.like(StringUtils.isNotBlank(username),"username", "%"+username+"%")//模糊查询
.like(StringUtils.isNotBlank(email),"email", "%"+email+"%")
.ge(age!=null,"age",age)//大于等于
.eq(departmentId!=null,"department.id",departmentId)
.build();
return specification;
}
getset………………
}