赞
踩
我在写自己的课程设计的时候,用的持久层API就是JPA。整个项目给我带来的感受就是:低SQL语句开发,甚至是零SQL语句开发,使得我在开发过程中,不再关注SQL语句的书写问题与逻辑问题。这使得我在开发过程中,更加专注于自己的业务逻辑,而不在拘泥于SQL表和Java实体之间的映射。尤其在多表查询这一块,JPA以其超简洁的语法规则,给我们实现了表一对一乃至一对多的关系。那么今天想给大家分享的是,一对一的多表查询。
以下引用了网上对JPA的介绍:
JPA是Java Persistence API的简称,中文名为Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
Spring Data Common是Spring Data所有模块的公用部分,该项目提供跨Spring数据项目的共享基础设施。它包含了技术中立的库接口以及一个坚持java类的元数据模型。
Spring Data不仅对传统的数据库访问技术JDBC、Hibernate、JDO、TopLick、JPA、Mybitas做了很好的支持、扩展、抽象、提供方便的API,还对NoSQL等非关系数据做了很好的支持,包括MongoDB、Redis、Apache Solr等。
首先我们使用的环境是Spring Boot环境。相信读者都应该会新建一个springboot的项目了,因此以下进行简单的环境搭建截图:
这里需要注意一下,我用的版本是2.6.0版本。
创建表的SQL语句如下所示:
值得注意的是,这里的students表的外键是teacher_id,它关联的是teacher表的teacher_id。
- SET FOREIGN_KEY_CHECKS=0;
- -- ----------------------------
- -- Table structure for student
- -- ----------------------------
- DROP TABLE IF EXISTS `student`;
- CREATE TABLE `student` (
- `id` int(10) NOT NULL AUTO_INCREMENT,
- `stu_no` varchar(20) NOT NULL,
- `stu_name` varchar(50) DEFAULT NULL,
- `teacher_id` int(10) NOT NULL,
- PRIMARY KEY (`id`),
- KEY `teacher_id` (`teacher_id`),
- CONSTRAINT `student_ibfk_1` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`teacher_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-
- -- ----------------------------
- -- Records of student
- -- ----------------------------
- INSERT INTO `student` VALUES ('1', 'stu01', '柏拉图', '1');
- INSERT INTO `student` VALUES ('2', 'stu01', '亚里士多德', '1');
-
- -- ----------------------------
- -- Table structure for teacher
- -- ----------------------------
- DROP TABLE IF EXISTS `teacher`;
- CREATE TABLE `teacher` (
- `teacher_id` int(10) NOT NULL AUTO_INCREMENT,
- `teacher_name` varchar(50) DEFAULT NULL,
- PRIMARY KEY (`teacher_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-
- -- ----------------------------
- -- Records of teacher
- -- ----------------------------
- INSERT INTO `teacher` VALUES ('1', '苏格拉底');

- package cn.com.demo.springdatajpa.pojo;
-
- import jdk.nashorn.internal.objects.annotations.Getter;
- import jdk.nashorn.internal.objects.annotations.Setter;
-
- import javax.persistence.*;
-
- // 该注解目的是为了标记他为一个实体类
- @Entity
- // 映射数据库中的student表
- @Table(name = "student")
- public class student {
-
- //标记为主键
- @Id
- // 申明主键生成策略 自动增长
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- // 将此属性与数据库表中的stu_no进行对应
- @Column(name = "stu_no")
- private String stuNo;
- @Column(name = "stu_name")
- private String stuName;
- @Column(name = "teacher_id")
- private String teacherId;
-
- public Integer getId() {
- return id;
- }
-
- public String getStuNo() {
- return stuNo;
- }
-
- public String getStuName() {
- return stuName;
- }
-
- public String getTeacherId() {
- return teacherId;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public void setStuNo(String stuNo) {
- this.stuNo = stuNo;
- }
-
- public void setStuName(String stuName) {
- this.stuName = stuName;
- }
-
- public void setTeacherId(String teacherId) {
- this.teacherId = teacherId;
- }
-
- @Override
- public String toString() {
- return "student{" +
- "id=" + id +
- ", stuNo='" + stuNo + '\'' +
- ", stuName='" + stuName + '\'' +
- ", teacherId='" + teacherId + '\'' +
- '}';
- }
- }

- package cn.com.demo.springdatajpa.pojo;
-
- import javax.persistence.*;
-
- @Entity
- @Table(name = "teacher")
- public class teacher {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer teacherId;
-
- @Column(name = "teacher_name")
- private String teacherName;
-
- public Integer getTeacherId() {
- return teacherId;
- }
-
- public void setTeacherId(Integer teacherId) {
- this.teacherId = teacherId;
- }
-
- public String getTeacherName() {
- return teacherName;
- }
-
- public void setTeacherName(String teacherName) {
- this.teacherName = teacherName;
- }
-
- @Override
- public String toString() {
- return "teacher{" +
- "teacherId=" + teacherId +
- ", teacherName='" + teacherName + '\'' +
- '}';
- }
- }

- package cn.com.demo.springdatajpa.dao;
- import cn.com.demo.springdatajpa.pojo.teacher;
- import org.springframework.data.jpa.repository.JpaRepository;
- import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
-
- public interface teacherDao extends JpaRepository<teacher,Integer>, JpaSpecificationExecutor<teacher> {
- }
- package cn.com.demo.springdatajpa.dao;
-
- import cn.com.demo.springdatajpa.pojo.student;
- import org.springframework.data.jpa.repository.JpaRepository;
- import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
-
- public interface studentDao extends JpaRepository<student,Integer>, JpaSpecificationExecutor<student> {
-
- }
1、在application.properties里面进行数据库的配置和jpa的配置
- # 配置数据的连接信息
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/school&useUnicode=true&characterEncoding=utf8
- spring.datasource.username=root
- spring.datasource.password=root
-
- spring.jpa.show-sql=true
- spring.jpa.hibernate.ddl-auto=update
- spring.jpa.database=MySQL
- spring.jpa.generate-ddl=true
- spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
2、在test目录下的SpringDataJPATest中进行测试
- package cn.com.demo.springdatajpa;
-
- import cn.com.demo.springdatajpa.dao.studentDao;
- import cn.com.demo.springdatajpa.dao.teacherDao;
- import cn.com.demo.springdatajpa.pojo.student;
- import cn.com.demo.springdatajpa.pojo.teacher;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- @SpringBootTest
- class SpringDataJpaApplicationTests {
-
- @Autowired
- private teacherDao teacherDao;
-
- @Autowired
- private studentDao studentDao;
-
- @Test
- void contextLoads() {
- List<teacher> teachers= teacherDao.findAll();
- List<student> students= studentDao.findAll();
- System.out.println("学生:"+students);
- System.out.println("教师:"+teachers);
- }
-
- }

我们来看看测试结果:
在上面的结果中,我们很明显的看到,两张表的数据是没有任何关联的。那么要实现一对一的表关联,我们就要确认在哪一方添加一个关联对象。很明显我们需要在有外键的一方,添加外键,添加的语句就是
- @JoinColumn(name = "teacher_id",insertable = false,updatable = false)
- @OneToOne(targetEntity=teacher.class,cascade=CascadeType.DETACH)
- private teacher teacher;
其中@JoinColumn表示添加一个查询字段,整个字段要以teacher_id作为关联查询条件,并且insertable和updateable表示不更新此字段。@OneToOne注解则表示:如果更具teacher_id查询到一个关联的结果集,就把他封装成teacher这个实体,并且他的级联级别是DETACH(级联实体分离操作),也就是说:分离所有相关联的实体,该实体已在数据库中,对象将处于分离状态,对该对象的操作不会同步到数据库。
除此之外,级联级别还包括:
ALL(
级联所有实体状态转换)
PERSIST(
级联实体持久化操作)
MERGE(
级联实体合并操作)
REMOVE(
级联实体删除操作)
REFRESH(
级联实体刷新操作)
因此,我们就把实体类student变成这个样子
- package cn.com.demo.springdatajpa.pojo;
-
- import jdk.nashorn.internal.objects.annotations.Getter;
- import jdk.nashorn.internal.objects.annotations.Setter;
-
- import javax.persistence.*;
-
- // 该注解目的是为了标记他为一个实体类
- @Entity
- // 映射数据库中的student表
- @Table(name = "student")
- public class student {
-
- //标记为主键
- @Id
- // 申明主键生成策略 自动增长
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- // 将此属性与数据库表中的stu_no进行对应
- @Column(name = "stu_no")
- private String stuNo;
- @Column(name = "stu_name")
- private String stuName;
- @Column(name = "teacher_id")
- private String teacherId;
-
- @JoinColumn(name = "teacher_id",insertable = false,updatable = false)
- @OneToOne(targetEntity=teacher.class,cascade=CascadeType.DETACH)
- private teacher teacher;
-
-
- public cn.com.demo.springdatajpa.pojo.teacher getTeacher() {
- return teacher;
- }
-
- public void setTeacher(cn.com.demo.springdatajpa.pojo.teacher teacher) {
- this.teacher = teacher;
- }
-
- public Integer getId() {
- return id;
- }
-
- public String getStuNo() {
- return stuNo;
- }
-
- public String getStuName() {
- return stuName;
- }
-
- public String getTeacherId() {
- return teacherId;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public void setStuNo(String stuNo) {
- this.stuNo = stuNo;
- }
-
- public void setStuName(String stuName) {
- this.stuName = stuName;
- }
-
- public void setTeacherId(String teacherId) {
- this.teacherId = teacherId;
- }
-
- @Override
- public String toString() {
- return "student{" +
- "id=" + id +
- ", stuNo='" + stuNo + '\'' +
- ", stuName='" + stuName + '\'' +
- ", teacherId='" + teacherId + '\'' +
- ", teacher=" + teacher +
- '}';
- }
- }

我们回到SpringDataJpaApplicationTests中进行测试,用一下代码进行测试
- package cn.com.demo.springdatajpa;
-
- import cn.com.demo.springdatajpa.dao.studentDao;
- import cn.com.demo.springdatajpa.dao.teacherDao;
- import cn.com.demo.springdatajpa.pojo.student;
- import cn.com.demo.springdatajpa.pojo.teacher;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- @SpringBootTest
- class SpringDataJpaApplicationTests {
-
- @Autowired
- private studentDao studentDao;
-
- @Test
- void contextLoads() {
- List<student> students= studentDao.findAll();
- for (student stu:students){
- System.out.println("学生姓名:"+stu.getStuName()+",他的老师姓名: "+stu.getTeacher().getTeacherName());
- }
- }
-
- }

测试结果:
我们就可以发现,学生对应的老师姓名,就出来啦。
好啦,这就是jpa的一对一关联,你是不是发现很简单呢。不需要一条SQL语句就可以轻松实现啦!假如你学废了,看懂的话,给我点个赞哦!爱你!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。