智能商贸系统day1(Spring+SpringMVC+SpringDataJPA)
一:项目搭建
1.使用ideal搭建项目—maven项目选择webapp
2. 完整结构为
3. 导入项目需要的jar依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<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.3</org.slf4j.version>
</properties>
<dependencies>
<!-- Spring的支持包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<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>4.2.4.RELEASE</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>
<!-- SpringDataJPA的支持包 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- SpringDataJPA的擴展包 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有的依賴都去掉 -->
<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包增强 -->
<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>
`
4 创建applicationContext.xml配置文件配置如下
<?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"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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="cn.itsource.aisale.service"/>
<!--导入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!--使用jpa-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<!--扫描domain包-->
<property name="packagesToScan" value="cn.itsource.aisale.domain"/>
<!--配置一个适配器-->
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
</property>
</bean>
<!--配置事务-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--事务注解支持-->
<tx:annotation-driven />
<!--扫描包-->
<jpa:repositories base-package="cn.itsource.aisale.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager">
</jpa:repositories>
</beans>
5 建立程序结构
6 完成实体类—由于主键id很多类都需要,抽取一个父类专门实现主键id
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/*
使用@MappedSuperclass注解,通过这个注解,我们可以将该实体类当成基类实体
在这里插入代码片,它不会映射到数据库表,
但继承它的子类实体在映射时会自动扫描该基类实体的映射属性,
添加到子类实体的对应数据库表中。
*/
@MappedSuperclass
public class BaseDomain {
@Id
@GeneratedValue
protected Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
7 Employee实体类类实现
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee extends BaseDomain {
//雇员姓名
private String username;
//雇员密码
private String password;
//雇员邮件
private String email;
//员工年龄
private Integer age;
@Override
public String toString() {
return "Employee{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", age=" + age +
", id=" + id +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
8 Repository(也就是Dao)层实现----SpringDataJPA进一步封装JPA,只需写一个接口继承一个接口即可完成crud操作。
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}
9 通过8可以完成一些简单的crud即分页排序与高级查询(通过根据规则写查询方法或者使用@Query注解)
规则如下:
public interface EmployeeRepository extends JpaRepository<Employee,Long>, JpaSpecificationExecutor<Employee> {
//通过定义的规则提供简单查询
List<Employee> findByUsernameLike(String username);
//使用query注解使用jpql或者sql语句查询
//@Query("select o from Employee o where o.username like ?1")
@Query(value = "select * from employee where username like ?",nativeQuery = true)
List<Employee> findUsername(String name);
List<Employee> findByUsernameLikeAndEmailLike(String username,String email);
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestEmployee {
@Autowired
private EmployeeRepository employeeRepository;
/*查询数据*/
@Test
public void testFind() throws Exception{
List<Employee> list = employeeRepository.findAll();
list.forEach(e -> System.out.println(e));
}
//添加数据
@Test
public void testAdd() throws Exception{
Employee employee = new Employee();
employee.setUsername("张三");
employee.setAge(12);
employee.setEmail("1e1a@qq.com");
employeeRepository.save(employee);
}
//修改数据
@Test
public void testUpdate() throws Exception{
Employee employee = new Employee();
employee.setUsername("张三");
employee.setAge(12);
employee.setId(274L);
employee.setEmail("1e1a@qq.com");
employeeRepository.save(employee);
}
//删除数据
@Test
public void testDelete() throws Exception{
employeeRepository.delete(274L);
}
//分页
@Test
public void testPage() throws Exception{
/*当前页从0开始*/
Pageable pageable=new PageRequest(0, 10);
Page<Employee> list = employeeRepository.findAll(pageable);
list.forEach(e-> System.out.println(e));
}
//排序
@Test
public void testOrder() throws Exception{
Sort sort=new Sort(Sort.Direction.ASC,"username");
List<Employee> li = employeeRepository.findAll(sort);
li.forEach(e-> System.out.println(e));
}
10 但是一些高级查询还是要写查询语句----这里继承JpaSpecificationExecutor接口可以不用写jpql便能完成高级查询,使用方法如下
//查询+排序+分页
@Test
public void testQuery3() throws Exception{
Sort sort=new Sort(Sort.Direction.ASC, "username");
Pageable pageable=new PageRequest(0, 10,sort);
Page<Employee> username = employeeRepository.findAll(new Specification<Employee>() {
/*
* root相当于类或者表
* cb相当于查询条件
* */
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//拿到要查询的字段
Path path = root.get("username");
//设置查询的值
Predicate like = cb.like(path, "%1%");
return like;
}
},pageable/*sort*/);
username.forEach(e-> System.out.println(e));
}
11 发现代码还是有点多—这里用了文浩大佬集成的一个jpa-specbao
导入依赖
<!-- SpringDatajpa的擴展包 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有的依賴都去掉 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
发现代码变得简单多了(具体使用请进入https://github.com/wenhao/jpa-spec查看)
//jpa-spec 分页+排序+查询
@Test
public void testQuery4() throws Exception{
Sort sort=new Sort(Sort.Direction.ASC, "username");
Pageable pageable=new PageRequest(0, 10,sort);
Specification<Employee> username = Specifications.<Employee>and()
.like("username","%1%")
.build();
Page<Employee> list = employeeRepository.findAll(username,pageable);
list.forEach(e-> System.out.println(e));
}
12 这里我们发现如果前台传入查询条件我们就必须要写一个类去接收
父类实现一些公共的查询条件(比如当前页,每页分页条数,排序类型–升序/降序,排序字段)
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
/*提供公共的查询条件
* 规范
* */
public abstract class BaseQuery {
/*一些公共的查询条件*/
//当前页
private int currentPage=1;
//当前页数量
private int pageSize=5;
//排序名称
private String OrderByname;
//排序类型
private String OrderByType= "ASC";
//获得从0开始的分页
public int getJpaCurrentPage(){
return this.currentPage-1;
}
/*规定子类必须实现这个方法,用来获得Specification对象*/
protected abstract Specification getSpec();
/*获得排序*/
public Sort getSort(){
Sort sort=null;
Sort.Direction desc = Sort.Direction.DESC;
if(StringUtils.isNoneBlank(OrderByname)){
if("ASC".equals(OrderByType.toUpperCase())){
//如果用户传入的是ASC
desc=Sort.Direction.ASC;
}
sort=new Sort(desc,OrderByname);
}
return sort;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int curentPage) {
this.currentPage = curentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getOrderByname() {
return OrderByname;
}
public void setOrderByname(String orderByname) {
OrderByname = orderByname;
}
public String getOrderByType() {
return OrderByType;
}
public void setOrderByType(String orderByType) {
OrderByType = orderByType;
}
}
import cn.itsource.aisale.domain.Employee;
import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
public class EmployeeQuery extends BaseQuery {
/*写自己独有的查询条件*/
private String username;
private String email;
private Integer age;
public String getUsername() {
return username;
}
//获得Specifications
public Specification<Employee> getSpec(){
Specification<Employee> spec = Specifications.<Employee>and()
/*问题:
* 因为无法判断用户是否传入条件,需要判断条件是否为空
* */
.like(StringUtils.isNoneBlank(username),"username",username)
.like(StringUtils.isNoneBlank(email),"email", email)
.lt(age!=null,"age",age)
.build();
return spec;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}