什么是JPA?
JPA(Java Persistence API)是 Sun 官方提出的 Java 持久化规范。它为 Java 开发人员提供了一种对象/关联映射工具来管理 Java 应用中的关系数据。它的出现主要是为了简化现有的持久化开发工作和整合 ORM 技术,结束现在 Hibernate、TopLink、JDO 等 ORM 框架各自为营的局面。值得注意的是,JPA 是在充分吸收了现有 Hibernate、TopLink、JDO 等 ORM 框架的基础上发展而来的,具有易于使用、伸缩性强等优点。从目前的开发社区的反应上看,JPA 受到了极大的支持和赞扬,其中就包括了 Spring 与 EJB 3.0 的开发团队。
注:第一部分为代码,第二部分为增删改查操作的截图和后台sql打印,完整代码可在github下载。
github地址:https://github.com/zjh746140129/Spring-Boot2.0
项目结构截图:
一、代码片段
1、实体类(学生类、成绩类、查询结果VO)
package com.boot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import java.io.Serializable;
import javax.persistence.*;
/**
* 学生类
* Created by zhoujh on 2018/6/14.
*/
@Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String name;
@Column(nullable = false)
private Integer age;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String address;
public Student() {
}
public Student(String name, Integer age, String email, String address) {
this.name = name;
this.age = age;
this.email = email;
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.boot.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
/**
* 成绩表
* Created by zhoujh on 2018/6/14.
*/
@Entity
public class Score implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(name = "PKUUID", strategy = "uuid")
@GeneratedValue(generator = "PKUUID")
private String id;
@Column(nullable = false)
private Long sid;
@Column(nullable = false)
private Double chineseScore;
@Column(nullable = false)
private Double mathScore;
@Column(nullable = false)
private Double englishScore;
public Score() {
}
public Score(Long sid, Double chineseScore, Double mathScore, Double englishScore) {
this.sid = sid;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getSid() {
return sid;
}
public void setSid(Long sid) {
this.sid = sid;
}
public Double getChineseScore() {
return chineseScore;
}
public void setChineseScore(Double chineseScore) {
this.chineseScore = chineseScore;
}
public Double getMathScore() {
return mathScore;
}
public void setMathScore(Double mathScore) {
this.mathScore = mathScore;
}
public Double getEnglishScore() {
return englishScore;
}
public void setEnglishScore(Double englishScore) {
this.englishScore = englishScore;
}
}
package com.boot.model;
import java.io.Serializable;
/**
* 用于接收学生表和成绩表查询信息
* Created by zhoujh on 2018/6/14.
*/
public class StudentInfo {
private String name;
private Integer age;
private Double chineseScore;
private Double mathScore;
private Double englishScore;
public StudentInfo() {
}
public StudentInfo(String name, Integer age, Double chineseScore, Double mathScore, Double englishScore) {
this.name = name;
this.age = age;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getChineseScore() {
return chineseScore;
}
public void setChineseScore(Double chineseScore) {
this.chineseScore = chineseScore;
}
public Double getMathScore() {
return mathScore;
}
public void setMathScore(Double mathScore) {
this.mathScore = mathScore;
}
public Double getEnglishScore() {
return englishScore;
}
public void setEnglishScore(Double englishScore) {
this.englishScore = englishScore;
}
}
2、编写service
package com.boot.service;
import com.boot.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* 学生类接口
* Created by zhoujh on 2018/6/14.
*/
public interface StudentService extends JpaRepository<Student, Long> {
//根据学生姓名查询
Student findByname(String name);
//根据学生姓名和地址查询
Student findByNameOrAddress(String name, String address);
//自定义sql查询
@Query("select s from Student s where s.name = ?1")
Student zdyFindByname(String name);
@Query("select s from Student s")
Page<Student> findALL(Pageable pageable);
Page<Student> findByName(String name, Pageable pageable);
}
package com.boot.service;
import com.boot.model.Score;
import com.boot.model.StudentInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Map;
/**
* 学生成绩接口
* Created by zhoujh on 2018/6/14.
*/
public interface StudentScoreService extends JpaRepository<Score, Long> {
@Query("select stu.name as name, stu.age as age, sc.chineseScore as chineseScore , sc.mathScore as mathScore,sc.englishScore as englishScore from Student stu , Score sc " +
"where stu.id = sc.sid and stu.name = ?1 ")
//List<StudentInfo> findStudentInfo(String name);
Map<String,Object> findStudentInfo(String name);
}
3、编写controller
package com.boot.controller;
import com.boot.model.Score;
import com.boot.model.Student;
import com.boot.model.StudentInfo;
import com.boot.service.StudentScoreService;
import com.boot.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 测试学生CRUD和两表联查
*/
@RestController
public class StudentController {
@Resource
private StudentService studentService;
@Resource
private StudentScoreService studentScoreService;
@RequestMapping("/crud")
public String studentCRUD() {
StringBuffer sb = new StringBuffer();
studentService.save(new Student("zhangsan", 18,"aa@126.com", "北京"));
studentService.save(new Student("lisi", 22,"lisi@126.com", "天津"));
studentService.save(new Student("wangwu", 19,"wangwu@126.com", "河北"));
//查询所有
System.out.println("总共有学生人数:"+studentService.findAll().size());
List<Student> studentList = studentService.findAll();
sb.append("新增的学生姓名:");
for (Student stu :studentList){
sb.append(stu.getName()+"\n");
}
//根据姓名和邮箱查询
Student student = studentService.findByNameOrAddress("zhangsan", "aa@126.com");
String stuName = student.getName();
System.out.println("根据姓名和邮箱查询到到学生是:"+student.getName());
sb.append("根据姓名和邮箱查询到到学生是:"+student.getName()+"\n");
student.setName("zhangsansan");
student.setName("zhangsansan");
Student newStu = studentService.save(student);
sb.append("修改"+stuName+"后姓名是:"+newStu.getName());
//删除一个学生
studentService.delete(studentService.findByname("wangwu"));
System.out.println("删除一个学生后总共有学生人数:"+studentService.findAll().size());
List<Student> newStudentList = studentService.findAll();
sb.append("删除一个学生后,剩下的的学生姓名是:");
for (Student stu :newStudentList){
sb.append(stu.getName()+"\n");
}
//默认查询方法
// studentService.findAll();
// studentService.findOne(1l);
// studentService.save(user);
// studentService.delete(user);
// studentService.count();
// studentService.exists(1l);
return sb.toString();
}
/**
* 两表联查
*/
@RequestMapping("/score")
public String findStudentAndScore(){
//studentScoreService.save(new Score(Long.parseLong("6"),88.5,92.0,78.0));
//List<StudentInfo> infoList = studentScoreService.findStudentInfo("zhangsansan");
//System.out.println("查询到zhangsansan"+infoList.size());
Map<String,Object> map = studentScoreService.findStudentInfo("zhangsansan");
StringBuffer sb = new StringBuffer();
sb.append("学生姓名:"+map.get("name"));
sb.append("学生年龄:"+map.get("age"));
sb.append("学生语文成绩:"+map.get("chineseScore"));
sb.append("学生数学成绩:"+map.get("mathScore"));
sb.append("学生英语成绩:"+map.get("englishScore"));
System.out.println("两表联查查询的学生成绩:"+sb.toString());
return sb.toString();
}
/**
* 分页查询
* @return
*/
@RequestMapping("/page")
public String findPageQuery(){
StringBuffer sb = new StringBuffer();
int page=0,size=2;
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(page, size, sort);
Page<Student> students = studentService.findALL(pageable);
System.out.println("分页查询的学生姓名:");
sb.append("分页查询的学生姓名:");
for (Student stu: students){
sb.append(stu.getName()+"\n");
System.out.println(stu.getName()+"\n");
}
// studentService.findByName("zhangsansan", pageable);
System.out.println("自定义sql查询的学生姓名是:");
sb.append("自定义sql查询的学生姓名是:");
Student student = studentService.zdyFindByname("zhangsansan");
sb.append(student.getName()+"\n");
System.out.println(student.getName()+"\n");
return sb.toString();
}
}
4、配置文件
Spring.datasource.url=jdbc:mysql://localhost:3306/jpa
Spring.datasource.username=root
Spring.datasource.password=root
Spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Spring.jpa.properties.hibernate.hbm2ddl.auto=update
Spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
Spring.jpa.show-sql= true
server.port=8089
5、启动类
package com.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootjpaApplication {
public static void main(String[] args) {
SpringApplication.run(BootjpaApplication.class, args);
}
}
6、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>
<groupId>com.boot</groupId>
<artifactId>bootjpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>bootjpa</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、演示增删改查
1、演示crud简单查询,页面打印如下
后台sql打印
2、两表联查页面打印
后台打印
3、分页查询和自定义sql查询,页面打印如下
后台打印