JPA之实体之间的关系

news2024/10/2 20:38:09

JPA之实体之间的关系

10.1.1实体类创建

注解的应用

@Table,@Entity

@Id+@GeneratedValue指定主键,@Column

P174 实体类编写规范

@Table(name = "t_user")
@Entity(name = "User")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    private Integer id;
    @Column(name = "name",length = 50,unique = false,insertable = true,updatable = true,table = "t_user",nullable = true)
    private String name;
+get和setter方法
+有参无参构造
+toSTring方法    
    
    }

10.1.2jap的一对一,一对多,多对多用法

详见10.1.3-10.1.9

10.1.3单向一对一

P188 结合课本的单向一对一进行判断

本人理解的单向一对一的关系是。

往person表插入数据或者是删除数据的时候可以对idcard表进行操作。

但是操作idcard表无论如何也得不到person表的任何信息。

案例:person和身份证实体

  • 通过用户可以找到身份证
  • 通过身份证不能找到用户
  • 关键是关系拥有方如何写

Person的代码:

@Table(name = "person")
@Entity(name="Person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "personId")
    private Integer personId;

    @Column(name="personName")
    private String personName;
//    ================单项一对一==============
    @OneToOne(optional = true,cascade = CascadeType.ALL)
    @JoinColumn(name = "id_card")
    private IdCard idCard;

//构造函数+getter+setter+toString
...
}

IdCard的代码:就是编写一个实体类

@Table(name = "idcard")
@Entity(name="IdCard")
public class IdCard {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cardId")
    private Integer cardId;

    @Column(name="cardName")
    private String cardName;
//构造函数+getter+setter

测试代码:

import com.lxz.demo2.entity.IdCard;
import com.lxz.demo2.entity.Person;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class PersonTest {
    public static void main(String[] args) {
        EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        transaction.begin();
        Person person=new Person(null,"李四");
        IdCard idCard=new IdCard(null,"李四身份证号码");
        person.setIdCard(idCard);
        em.persist(person);
        transaction.commit();
    }

}

效果图:

10.1.4双向一对一

1.双向一对一

本人理解的双向一对一的关系是。

往person表插入数据或者是删除数据的时候可以对idcard表进行操作。

操作idcard表同样也会操作person表。

1.Person表的代码不变

@Table(name = "t_person")
@Entity(name="Person1")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "personId")
    private Integer personId;

    @Column(name="personName")
    private String personName;
//    ================单项一对一==============
    @OneToOne(optional = true,cascade = CascadeType.ALL)
    @JoinColumn(name = "card_id")
    private IdCard idCard;}

2.IdCard的代码

@Table(name = "t_card")
@Entity(name="IdCard")
public class IdCard {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cardId")
    private Integer cardId;

    @Column(name="cardName")
    private String cardName;
//    =============双向一对一===================
//    mappedBy必须和前面设置的保持一致,idCard是person的属性,所以person表是关系的维护方
    @OneToOne(optional = false,cascade = CascadeType.REFRESH,mappedBy = "idCard")
    private Person person;

//构造函数+getter+setter
}

测试代码:

public class PersonTest {
    public static void main(String[] args) {
        EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        transaction.begin();
        TPerson person=new TPerson(null,"王五");
        TIdCard idCard=new TIdCard(null,"李四身份证号码");
        person.setIdCard(idCard);
        idCard.settPerson(person);
        em.persist(person);
        em.persist(idCard);
        transaction.commit();
    }

}

效果图:

10.1.5单向一对多

3.单向一对多

P193 单向一对多关系

案例:部门和员工的关系就是一对多的关系

  • 外键关联
  • 中间表

1.采用外键关联的方式

  • 创建表

Department表:

Employee表:

  • 创建

  • 测试:

 EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        transaction.begin();
        Department department=new Department(null,"媒体部",null);
        Employee employee=new Employee(null,"王五");
        Employee employee2=new Employee(null,"赵六");
        List<Employee> e=new ArrayList<>();
        e.add(employee);
        e.add(employee2);
        department.setEmployees(e);
        em.persist(department);
        transaction.commit();

2.基于中间表方式

案例:学生和选课之间的关系是就是单向一对一,一个学生可以选择多门课程可以形成一个中间表(选课信息表)

基于中间表的方式的区别和基于外键的区别在于配置单方(关系拥有方的时候需要配置中间表)

  • student类

@Table(name = "student")
@Entity(name = "Student")
public class Student implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name="sc",
            joinColumns={
                    @JoinColumn(name = "student_id", referencedColumnName = "id")}
            ,inverseJoinColumns = {
            @JoinColumn(name = "course_id", referencedColumnName = "id")
    })

    List<Course> courses;
    }

  • Course类:

@Entity(name = "Course")
@Table(name = "course")
public class Course {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    }

  • 测试类:

 EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        transaction.begin();
        Student student=new Student(null,"张三",null);
        Course c1=new Course(null,"数据库");
        Course c2=new Course(null,"Java");
        List<Course> e=new ArrayList<>();
        e.add(c1);
        e.add(c2);
        student.setCourses(e);
        em.persist(student);
        transaction.commit();

查询测试:

  public static void main(String[] args) {
       EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
       EntityManager em=factory.createEntityManager();
       Query query=em.createQuery("select student from Student student");
       System.out.println(query.getResultList());

   }

  • 查多端的

public static void main(String[] args) {
       EntityManagerFactory factory=Persistence.createEntityManagerFactory("MyJPA2");
       EntityManager em=factory.createEntityManager();
       Query query=em.createQuery("select course from Course course");
       System.out.println(query.getResultList());

   }

10.1.6单向多对一/

1.单向一对多

10.1.7双向一对多/双向多对一

P193

从一方可以获取多方,从多方可以获取一方

@ManyToOne注解+@OneToMany注解的应用

  • Student类:

@Table(name = "student")
@Entity(name = "Student")
public class Student implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    List<Course> courses;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Course> getCourses() {
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }

    public Student() {
    }

    public Student(Integer id, String name, List<Course> courses) {
        this.id = id;
        this.name = name;
        this.courses = courses;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", courses=" + courses +
                '}';
    }
}

  • Course类

@Entity(name = "Course")
@Table(name = "course")
public class Course {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinTable(name="sc",
            joinColumns={
                    @JoinColumn(name = "course_id", referencedColumnName = "id")}
            ,inverseJoinColumns = {
            @JoinColumn(name = "student_id", referencedColumnName = "id")
    })
     private Student student;
    }

10.1.8单向多对多

P196

  • Student表

@Entity(name = "Student")
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name = "sc")
    private Collection<Course> course=new ArrayList();
    

}

  • course表:

@Entity(name = "theCourse")
@Table(name = "course")
public class Course {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

10.1.9双向多对多

P197

  • Student

@Entity(name = "Student")
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name = "sc")
    private Collection<Course> courses=new ArrayList();

  • Course

@Entity(name = "theCourse")
@Table(name = "course")
public class Course {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @ManyToMany(mappedBy = "courses",cascade = CascadeType.ALL)
    private Collection<Student> students;

10.1.10jpa单表的增删改查

  • 目录

  • 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
     http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="MyJPA" transaction-type="RESOURCE_LOCAL">
      <class>com.lxz.demo.entity.User</class>
        <properties>
            <!-- 标准配置方法,适用性高 -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jdbc?useSSL=false&amp;serverTimezone=GMT"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value="root"/>

            <!-- hibernate 的配置方法-->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update"/> <!--create,create-drop,update,validate  -->

        </properties>
    </persistence-unit>
</persistence>

  • 实体类

@Table(name = "t_user")
@Entity(name = "User")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    private Integer id;
    @Column(name = "name",length = 50,unique = false,insertable = true,updatable = true,table = "t_user",nullable = true)
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User() {
    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

  • UserDao类

public class UserDao {
    public boolean add(User user){
        try {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyJPA");
            EntityManager em = factory.createEntityManager();
            EntityTransaction transaction = em.getTransaction();
            transaction.begin();
            em.persist(user);
            transaction.commit();
            em.close();
            factory.close();
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean update(User user){
        try {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyJPA");
            EntityManager em = factory.createEntityManager();
            EntityTransaction transaction = em.getTransaction();
            transaction.begin();
            em.merge(user);
            transaction.commit();
            em.close();
            factory.close();
            return true;
        }
        catch (Exception e){
            return false;
        }
    }
    public boolean delete(Integer id){
        try {
        EntityManagerFactory factory= Persistence.createEntityManagerFactory("MyJPA");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        transaction.begin();
        User user=new User();
        user=em.find(User.class,id);
        em.remove(user);
        transaction.commit();
        em.close();
        factory.close();
        return true;
        }
        catch (Exception e){
            return false;
        }
    }
    public User findById(Integer id){
        EntityManagerFactory factory= Persistence.createEntityManagerFactory("MyJPA");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        User user=em.find(User.class,id);
        em.close();
        factory.close();
        return user;
    }
    public List<User> findAll(){
        EntityManagerFactory factory= Persistence.createEntityManagerFactory("MyJPA");
        EntityManager em=factory.createEntityManager();
        EntityTransaction transaction=em.getTransaction();
        Query query =em.createQuery("select user from User user");
        List<User> users=query.getResultList();
        em.close();
        factory.close();
        return users;
    }
}

  • 测试类

public class UserDaoTest {
    public static void main(String[] args) {
        UserDao userDao=new UserDao();
        System.out.println(userDao.add(new User(null,"add")));
        System.out.println(userDao.update(new User(2,"update")));
        System.out.println(userDao.delete(9));
        System.out.println(userDao.findAll());
        System.out.println(userDao.findById(2));
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/380238.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

王道操作系统课代表 - 考研计算机 第二章 进程与线程 究极精华总结笔记

本篇博客是考研期间学习王道课程 传送门 的笔记&#xff0c;以及一整年里对 操作系统 知识点的理解的总结。希望对新一届的计算机考研人提供帮助&#xff01;&#xff01;&#xff01; 关于对 “进程与线程” 章节知识点总结的十分全面&#xff0c;涵括了《操作系统》课程里的全…

机器学习——线性学习

提及线性学习&#xff0c;我们首先会想到线性回归。回归跟分类的区别在于要预测的目标函数是连续值线性回归假定输入空间到输出空间的函数映射成线性关系&#xff0c;但现实应用中&#xff0c;很多问题都是非线性的。为拓展其应用场景&#xff0c;我们可以将线性回归的预测值做…

SQL的优化【面试工作】

SQL的优化 最近看到群友在讨论这块的优化,感觉不管工作和面试,都是用上的,记录下吧!(不然又记不住) 优化点: 处理和优化复杂的 SQL 查询可以有以下几个方向&#xff1a; 1.优化查询语句本身 首先&#xff0c;可以优化 SQL 查询语句本身&#xff0c;尽量让其更加简洁、高效。 …

Go程序当父进程被kill,子进程也自动退出的问题记录

平常我们启动一个后台进程&#xff0c;会通过nouhp &的方式启动&#xff0c;这样可以在退出终端会话的时候&#xff0c;进程仍然可以继续在后台执行(进程的父进程id会从原来的bash进程变成1) 在go程序中&#xff0c;通过nouhp &的方式启动子进程&#xff0c;预期是即使…

干货| Vue小程序开发技术原理

目前应用最广的三大前端框架分别是Vue、 React 和 Angular 。其中&#xff0c;不管是 BAT 大厂&#xff0c;还是创业公司&#xff0c;Vue 都有广泛的应用。如今&#xff0c;再随着移动开发小程序的蓬勃发展&#xff0c;Vue也广泛应用到了小程序开发当中。今天&#xff0c;就来详…

嵌入式 STM32 SHT31温湿度传感器

目录 简介 1、原理图 2、时序说明 数据传输 起始信号 结束信号 3、SHT31读写数据 SHT31指令集 读数据 温湿度转换 4、温湿度转换应用 sht3x初始化 读取温湿度 简介 什么是SHT31&#xff1f; 一主机多从机--通过寻址的方式--每个从机都有唯一的地址&…

linux--多线程(一)

文章目录Linux线程的概念线程的优点线程的缺点线程异常线程的控制创建线程线程ID以及进程地址空间终止线程线程等待线程分离线程互斥进程线程间的互斥相关概念互斥量mutex有线程安全问题的售票系统查看ticket--部分的汇编代码互斥量的接口互斥量实现原理探究可重入和线程安全常…

三重积分为何不能直接带入积分区域?搞懂这些,重积分基本可以了

积分的积分区域及被积表达式 重点&#xff1a;积分的结果均为数值&#xff0c;仅与被积表达式和积分区间有关&#xff01;&#xff01;&#xff01; 1.如何一下子区分一重积分&#xff0c;二重积分&#xff0c;三重积分&#xff1f; 看积分区间和被积表达式&#xff1a; 一重…

React教程详解一(props、state、refs、生命周期)

文章略长&#xff0c;耐心读完&#xff0c;受益匪浅哦~ 目录 前言 简介 JSX 面向组件编程 state props refs 组件生命周期 前言 简介 React框架由Facebook开发&#xff0c;和Vue框架一样&#xff0c;都是用于构建用户界面的JavaScript库&#xff1b; 它有如下三个特…

PHP - ChatGpt 学习 仅供参考

由于最近ChatGpt 大火&#xff0c;但是门槛来说是对于大家最头疼的环节&#xff0c; 由此ChatGpt 有一个API 可以仅供大伙对接 让我来说下资质&#xff1a; 1&#xff1a;首先要搞得到一个 ChatGpt 的账户&#xff0c; 会获得一个KEY&#xff0c;该key为访问API核心&#xff0…

jenkins漏洞集合

目录 CVE-2015-8103 反序列化远程代码执行 CVE-2016-0788 Jenkins CI和LTS 远程代码执行漏洞 CVE-2016-0792 低权限用户命令执行 CVE-2016-9299 代码执行 CVE-2017-1000353 Jenkins-CI 远程代码执行 CVE-2018-1000110 用户枚举 CVE-2018-1000861 远程命令执行 CVE-2018…

ChatGPT文章自动发布WordPress

WordPress可以用ChatGPT发文章吗&#xff1f;答案是肯定的&#xff0c;ChatGPT官方有提供api接口&#xff0c;多以目前有很多的SEO工具具有自动文章生成自动发布的功能&#xff0c;使用SEO工具&#xff0c;我们可以通过疑问词和关键词进行文章生成&#xff0c;并定时发布到我们…

软测入门(三)Selenium(Web自动化测试基础)

Selenium&#xff08;Web端自动测试&#xff09; Selenium是一个用于Web应用程序测试的工具&#xff1a;中文是硒 开源跨平台&#xff1a;linux、windows、mac核心&#xff1a;可以在多个浏览器上进行自动化测试多语言 Selenium WebDriver控制原理 Selenium Client Library…

Linux基础——连接Xshell7

个人简介&#xff1a;云计算网络运维专业人员&#xff0c;了解运维知识&#xff0c;掌握TCP/IP协议&#xff0c;每天分享网络运维知识与技能。座右铭&#xff1a;海不辞水&#xff0c;故能成其大&#xff1b;山不辞石&#xff0c;故能成其高。个人主页&#xff1a;小李会科技的…

复位理论基础

先收集资料&#xff0c;了解当前常用的基础理论和实现方式 复位 初始化微控制器内部电路 将所有寄存器恢复成默认值确认MCU的工作模式禁止全局中断关闭外设将IO设置为高阻输入状态等待时钟趋于稳定从固定地址取得复位向量并开始执行 造成复位的原因 有多种引起复位的因素&…

客户关系管理挑战:如何保持客户满意度并提高业绩?

当今&#xff0c;各行业市场竞争愈发激烈&#xff0c;对于保持客户满意度并提高业绩是每个企业都面临的挑战。而客户关系管理则是实现这一目标的关键&#xff0c;因为它涉及到与客户的互动和沟通&#xff0c;以及企业提供优质的产品和服务。在本文中&#xff0c;我们将探讨客户…

使用Geth搭建多节点私有链

使用Geth搭建多节点私有链 步骤 1.编辑初始化配置文件genesis.json {"config": {"chainId": 6668,"homesteadBlock": 0,"eip150Block": 0,"eip150Hash": "0x000000000000000000000000000000000000000000000000000000…

JDK下载安装与环境

&#x1f972; &#x1f978; &#x1f90c; &#x1fac0; &#x1fac1; &#x1f977; &#x1f43b;‍❄️&#x1f9a4; &#x1fab6; &#x1f9ad; &#x1fab2; &#x1fab3; &#x1fab0; &#x1fab1; &#x1fab4; &#x1fad0; &#x1fad2; &#x1fad1;…

回暖!“数”说城市烟火气背后

“人间烟火气&#xff0c;最抚凡人心”。在全国各地政策支持以及企业的积极生产运营下&#xff0c;经济、社会、生活各领域正加速回暖&#xff0c;“烟火气”在城市中升腾&#xff0c;信心和希望正在每个人心中燃起。 发展新阶段&#xff0c;高效统筹经济发展和公共安全&#…

JavaEE进阶第六课:SpringBoot配置文件

上篇文章介绍了SpringBoot的创建和使用&#xff0c;这篇文章我们将会介绍SpringBoot配置文件 目录1.配置文件的作用2.配置文件的格式2.1 .properties语法2.1.1.properties的缺点2.2 .yml语法2.2.1优点分析2.2.2配置与读取对象2.2.3配置与读取集合2.2.4补充说明3.设置不同环境的…