Spring Data JPA简介:

可以理解为 JPA 规范的再次封装抽象,底层还是使用了 Hibernate 的 JPA 技术实现,引用 JPQL(Java Persistence Query Language)查询语言,属于 Spring 的整个生态体系的一部分。

优势:

属于 Spring 的整个生态体系的一部分上手简单、开发效率高,ORM提供的能力他都提供,ORM框架没有提供的业务逻辑功能Spring-data-jpa也提供,全方位的解决用户的需求。使用Spring-data-jpa进行开发的过程中,常用的功能,我们几乎不需要写一条sql语句。

Spring Data操作主要特性:

提供模板操作,如 Spring Data Redis 和 Spring Data Riak;

强大的 Repository 和定制的数据储存对象的抽象映射;

对数据访问对象的支持(Auting 等)。

Spring Data JPA 的主要类及结构图:

七个大 Repository 接口:

Repository(org.springframework.data.repository);

CrudRepository(org.springframework.data.repository);

PagingAndSortingRepository(org.springframework.data.repository);

JpaRepository(org.springframework.data.jpa.repository);

QueryByExampleExecutor(org.springframework.data.repository.query);

JpaSpecificationExecutor(org.springframework.data.jpa.repository);

QueryDslPredicateExecutor(org.springframework.data.querydsl)。

两大 Repository 实现类:

SimpleJpaRepository(org.springframework.data.jpa.repository.support);

QueryDslJpaRepository(org.springframework.data.jpa.repository.support)。

Quick start:

以spring-boot2.1.3 ,mysql5.5+ 为技术场景

开发环境:

SPRING STS,MAVEN3.0+,JDK1.8

1、创建sringboot工程

完整工程结构图如下:

pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhengjiang</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
<!-- import lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build> </project>

2、修改application.properties 为yml配置

 spring:
profiles:
active: product
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
username: root
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: UTC

创建实体类UserInfo:

 package com.zhengjiang.springboot.demo.entity;

 import java.util.Date;

 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data;
import lombok.ToString; @Data
@ToString
@Entity
@Table(name = "t_sys_user")
@Component
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class UserInfo{ public UserInfo() {} public UserInfo(String name) {this.name = name;}
@Id
@GeneratedValue
private Long id; //ID
private String name; //姓名
private String jobNumber; //工号
private Date createTime; //创建时间
}

创建一个 Repository

 package com.zhengjiang.springboot.demo.respository;

 import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.zhengjiang.springboot.demo.entity.UserInfo; public interface UserRepository extends JpaRepository<UserInfo, Long>,JpaSpecificationExecutor<UserInfo> {
UserInfo findByName(String name);
}

创建service 以及实现类

 package com.zhengjiang.springboot.demo.service;

 import java.util.List;

 import org.springframework.data.domain.Page;

 import com.zhengjiang.springboot.demo.entity.UserInfo;

 public interface UserService {

     UserInfo findById(Long id);
List<UserInfo> getUserList();
UserInfo getUserByName(String name);
UserInfo addUserInfo(UserInfo userInfo);
UserInfo updateUserInfoById(UserInfo userInfo);
void deleteUserInfoById(Long Id);
List<UserInfo>getCurrentUserList();
Page<UserInfo> getPageUserList();
}
 package com.zhengjiang.springboot.demo.service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageRequest; import com.zhengjiang.springboot.demo.entity.UserInfo;
import com.zhengjiang.springboot.demo.respository.UserRepository;
import com.zhengjiang.springboot.demo.service.UserService; @Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository; @Override
public UserInfo findById(Long id) {
return userRepository.getOne(id);
}
@Override
public List<UserInfo> getUserList() {
return userRepository.findAll();
} @Override
public UserInfo getUserByName(String name) {
UserInfo userInfo = userRepository.findByName(name);
return userInfo;
} @Override
public UserInfo addUserInfo(UserInfo userInfo) {
return userRepository.save(userInfo);
} @Override
public UserInfo updateUserInfoById(UserInfo userInfo) {
return userRepository.save(userInfo);
} @Override
public void deleteUserInfoById(Long id) {
userRepository.deleteById(id);
} @Override
public List<UserInfo> getCurrentUserList() {
Sort sort=new Sort(Sort.Direction.DESC,"createTime");
return userRepository.findAll(sort);
}
@Override
public Page<UserInfo> getPageUserList() {
Sort sort=new Sort(Sort.Direction.DESC,"createTime");
PageRequest pageable=new PageRequest(0,5,sort);
userRepository.findAll(pageable);
return userRepository.findAll(pageable);
}
}

创建controller

 package com.zhengjiang.springboot.demo.controller;

 import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zhengjiang.springboot.demo.entity.UserInfo;
import com.zhengjiang.springboot.demo.service.UserService; @RestController
@RequestMapping("/test")
public class TestController { @Autowired
private UserService userService; /**
*
* @param id
* @return
*/
@GetMapping(value = "/getOne")
public UserInfo getOne(@RequestParam("id") Long id) {
return userService.findById(id);
} /**
* 获取所有用户
* @return
*/
@GetMapping(value = "/getUserList")
public List<UserInfo> getUserList() {
return userService.getUserList();
} /**
* 根据用户名查找
* @param name
* @return
*/
@GetMapping(value = "/getUserInfo")
public UserInfo getUserInfoByName(@RequestParam("name") String name) {
UserInfo u = userService.getUserByName(name);
return u;
} /**
* 根据createTime倒序查询
* @return
*/
@GetMapping(value = "/getCurrentUserList")
public List<UserInfo> getCurrentUserList(){
return userService.getCurrentUserList();
} /**
* 分页查找
* @return
*/
@GetMapping(value="/getPageUserList")
public Page<UserInfo> getPageUserList(){
return userService.getPageUserList();
} /**
* 添加用户
* @param userInfo
* @return
*/
@PostMapping(value = "/addUserInfo")
public UserInfo addUserInfo(UserInfo userInfo) {
return userService.addUserInfo(userInfo);
} /**
* 更新用户
* @param userInfo
* @return
*/
@PostMapping(value ="/updateUserInfo")
public UserInfo updateUserInfo(UserInfo userInfo){
return userService.updateUserInfoById(userInfo);
} /**
* 删除用户
* @param id
*/
@PostMapping(value="/deleteUserInfo")
public void deleteUserInfo(@RequestParam("id") Long id){
userService.deleteUserInfoById(id);
} @InitBinder
protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));/*TimeZone时区,解决差8小时的问题*/
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}

用postman 测试接口。

最新文章

  1. Java 加解密 AES DES TripleDes
  2. CSS3-样式继承,层叠管理,文本格式化
  3. vim实用技巧
  4. 面向切面编程AOP:基于注解的配置
  5. nginx二级域名配置
  6. 使用AngularJS 进行Hybrid App 开发已经有一年多时间了,这里做一个总结
  7. Update操作浅析,一定是先Delete再Insert吗?
  8. css的repaint和reflow
  9. 九度OJ题目1076:N的阶乘 (java)运用BigInteger的例子。
  10. HttpURLConnection实现两个服务端的对接
  11. 清流,获取点击的img路径
  12. phpstorm 安装yaf代码提示文件
  13. 学习 google file system 心得体会
  14. 动态创建radio、checkbox时需要注意的问题
  15. jetty异常
  16. [javaSE] 网络编程(TCP通信)
  17. Go语言-windows安装配置篇
  18. Python 把数据库的数据导出到excel表
  19. Redis 主从部署
  20. Qt 出现“undefined reference to `vtable for”原因总结

热门文章

  1. java简单打印金字塔(案例)
  2. Spring Boot (28) actuator与spring-boot-admin
  3. leetcode126 Word Ladder II
  4. switch-case用法
  5. Vue.js——router-link阻止click事件
  6. navicat创建存储过程报错
  7. 【转载】Caffe学习:运行caffe自带的两个简单例子
  8. webstom2017最新破解 ------------ http://blog.csdn.net/voke_/article/details/76418116
  9. 浅谈IFC
  10. 如何快速的vue init 属于自己的vue模板?