博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JPA(二):JPA 实体映射关系
阅读量:4104 次
发布时间:2019-05-25

本文共 11723 字,大约阅读时间需要 39 分钟。

映射关系思维导图

清晰思维导图分享地址为:

1.单向一对一映射

一个实体A与另一个实体B之间存在关系,通过A可以获得B,通过B不能获得A。

1.1.数据库

CREATE TABLE `user` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,    `password` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;CREATE TABLE `article` (    `articleId` int(11) NOT NULL AUTO_INCREMENT,    `articleName` varchar(255) DEFAULT NULL,    `articleContent` varchar(255) DEFAULT NULL,   PRIMARY KEY (`articleId`)   ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1.2.实体类

添加文章类和用户类

Article类

@Entity@Table(name = "article")public class Article  {    @Id    @GeneratedValue    @Column(name = "articleId")    private int article;    @Column    private String articleName;    @Column    private String articleContent;     //省略getter和setter}

User类

@Entity//指定表名,指定唯一约束@Table(name = "user",uniqueConstraints = {@UniqueConstraint(columnNames = {"id","name"})})public class User {    @Id//指定主键    @GeneratedValue    private int id;    @Column    private String name;    @Column    private String password;    //一对一映射    @OneToOne(optional = true, cascade = CascadeType.ALL)    @JoinColumn(name = "articleId", unique = true)    public Article article;   //省略getter和setter}

@JoinColumn(name = "articleId", unique = true),articleId是所对应的外键。

1.3.测试

@Test    public void testOneToOneRelevance(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        User user  = new User();        user.setName("hz");        Article article = new Article();        article.setAricleName("yx");        user.setArticle(article);        em.persist(user);        em.getTransaction().commit();        em.close();        entityManagerFactory.close();    }

2.单向一对多关系中间表方式实现

2.1.数据库

CREATE TABLE `author` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `authorName` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;CREATE TABLE `book` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `bookName` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;CREATE TABLE `public` (    `authorId` int(11) NOT NULL ,    `bookId` int(11) NOT NULL,   PRIMARY KEY (`authorId`,`bookId`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.2.实体类

实体类有作者,书籍,和作者所对应的出版的书籍

作者类

@Entitypublic class Author {    @Id    @GeneratedValue    private int id;    private String authorName;    /**     * Author和Book是一对多关系     */    @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)    //name:public中间表一方的外键名称    //referencedColumnName:public表的authorId外键参考了Author表的id主键    @JoinTable(name = "public",joinColumns = {@JoinColumn(name = "authorId",referencedColumnName = "id")},    //指定中间表多方外键    //name:中间表多方外键的名称为bookId    //referencedColumnName:bookId参考了book表的id主键    inverseJoinColumns = {@JoinColumn(name = "bookId",referencedColumnName = "id")})    private Collection
books;}

书籍类

@Entitypublic class Book {    @Id    @GeneratedValue    private int id;    private String bookName;}

出版类

public class Publish {    private int authorId;    private int bookId;}

2.3.测试方法

/**     * 双向一对多关系OneToMany中间表方式实现     */    @Test    public void testOneToManyRelevance(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        Author author = new Author();        author.setAuthorName("hly");        Book book1 = new Book();        Book book2 = new Book();        book1.setBookName("Java");        book2.setBookName("Linux");        Collection
collection = new ArrayList<>(); collection.add(book1); collection.add(book2); author.setBooks(collection); em.persist(author); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }

3.双向一对多关系外键关联方式实现

3.1.数据库

BOSS表和员工表

CREATE TABLE `boss` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `employee` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3.2.实体类

BOSS类

@Entitypublic class Boss {    @Id    @GeneratedValue    private int id;    private String name;    //多方设置指向一方的主键    //mappedBy:Boss类为多方关系维护方,负责数据库外键boss_id的更新    @OneToMany(cascade = CascadeType.ALL,mappedBy = "boss")    private Collection
employees = new ArrayList
();}

员工类

@Entitypublic class Employee {    @Id    @GeneratedValue    private int id;    private String name;    //todo 外键为null    @ManyToOne    @JoinColumn(name = "bossId")    private Boss boss;}

3.3.测试方法

/**     * 双向一对多关系OneToMany外键关联方式实现      */    @Test    public void testOneToManyForeignKeyLink(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        Boss boss = new Boss();        boss.setName("hly");        Employee employee1 = new Employee();        Employee employee2 = new Employee();        employee1.setName("aff");        employee2.setName("gbd");        Collection
collection = new ArrayList
(); collection.add(employee1); collection.add(employee2); boss.setEmployees(collection); employee1.setBoss(boss); employee2.setBoss(boss); em.persist(boss); em.persist(employee1); em.persist(employee2); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }

4.单向多对一关系

4.1.数据库

People表和Car表

CREATE TABLE `people` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `car` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4.2.实体类

People类

@Entitypublic class People {    @Id    @GeneratedValue    private int id;    private String name;}

Car类

@Entitypublic class Car {    @Id    @GeneratedValue    private int id;    private String name;    @ManyToOne(cascade = CascadeType.ALL)    private People people;}

这里没有用注解声明外键,自动生成的外键格式为people_id

4.3.测试方法

/**     * 单向多对一关系ManyToOne     */    @Test    public  void testManyToOneRelevance(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        Car car1 = new Car();        Car car2 = new Car();        People people  = new People();        car1.setName("Porsche");        car2.setName("Ferrari");        people.setName("hly");        car1.setPeople(people);        car2.setPeople(people);        em.persist(car1);        em.persist(car2);        em.getTransaction().commit();        em.close();        entityManagerFactory.close();    }

5.单向多对多关系

从多方A可以获得另外的多方B;从B不需要获得A

5.1.数据库

学生,课程,选课表

CREATE TABLE `student` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `studentName` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `course` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `courseName` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `selectcourse` (    `studentId` int(11) NOT NULL,    `courseId` int(11) NOT NULL,   PRIMARY KEY (`studentId`,`courseId`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

5.2.实体类

Couse类

@Entitypublic class Course {    @Id    @GeneratedValue    private int id;    private String courseName;}
Student类
@Entitypublic class Student {    @Id    @GeneratedValue    private int id;    private String studentName;    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)    @JoinTable(name = "selectCourse",joinColumns = {@JoinColumn(name = "studentId",referencedColumnName = "id")},            inverseJoinColumns = {@JoinColumn(name = "courseId",referencedColumnName = "id")})    private Collection
courses;}

选课类

public class SelectCourse {        private int studentId;    private int courseId;}

5.3.测试方法

/**     * 单向多对多关系ManyToMany     */    @Test    public void manyToManyOfSingleTrack(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        Student student = new Student();        student.setName("hly");        Course course1 = new Course();        Course course2 = new Course();        course1.setName("Java");        course2.setName("数据库");        Collection
courses = new ArrayList<>(); courses.add(course1); courses.add(course2); student.setCourses(courses); em.persist(student); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }

6.双向双向多对多关系

6.1.数据库

CREATE TABLE `classes` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `teacher` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `name` varchar(255) DEFAULT NULL,   PRIMARY KEY (`id`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE `teaching` (    `teacherId` int(11) NOT NULL,    `classesId` int(11) NOT NULL,   PRIMARY KEY (`teacherId`,`classesId`)   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

6.2.实体类

教师,班级,教师班级关系类

Teacher类

@Entitypublic class Teacher {    @Id    @GeneratedValue    private int id;    private String name;        @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)    @JoinTable(name = "teaching",joinColumns = {@JoinColumn(name = "teacherId",referencedColumnName = "id")},            inverseJoinColumns ={@JoinColumn(name = "classesId",referencedColumnName = "id")} )    private Collection
classes = new ArrayList
();}

Classes类

@Entitypublic class Classes {    @Id    @GeneratedValue    private int id ;    private String name;    //mapperBy为Teacher的Classes属性    @ManyToMany(mappedBy = "classes",cascade = CascadeType.ALL,fetch = FetchType.EAGER)    private Collection
teachers = new ArrayList
();}

Teaching类

public class Teaching {    //命名不是teacher_id格式需要在teacher类中@JoinTable里声明    private int classId;    private int teacherId;}

6.3.测试方法

/**     * 双向多对多ManyToMany     */    @Test    public void manyToManyOfDuple(){        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyJPA");        EntityManager em = entityManagerFactory.createEntityManager();        em.getTransaction().begin();        Teacher teacher1 = new Teacher();        Teacher teacher2 = new Teacher();        Classes classes1 = new Classes();        Classes classes2 = new Classes();        teacher1.setName("aaa");        teacher2.setName("bbb");        classes1.setName("161");        classes2.setName("162");        Collection
teachers = new ArrayList<>(); Collection
classes = new ArrayList<>(); teachers.add(teacher1); teachers.add(teacher2); classes.add(classes1); classes.add(classes2); teacher1.setClasses(classes); classes2.setTeachers(teachers); em.persist(teacher1); em.persist(classes2); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }

代码及地址

完整代码在笔者的,欢迎访问。

你可能感兴趣的文章
OpenCV meanshift目标跟踪总结
查看>>
人工神经网络——神经元模型介绍
查看>>
Windows 窗口底层原理
查看>>
一种函数指针的运用
查看>>
今天,Python信息量很大!
查看>>
Flash 已死,Deno 当立?
查看>>
编程差的程序员,90%都是吃了数学的亏!骨灰级开发:方法不对,努力也白费...
查看>>
都无代码了,还要程序员吗?
查看>>
面试想拿 10K,HR 说我只配7k?
查看>>
那些人生“开挂”的程序员,都在干什么?
查看>>
影响科学圈的那些计算机代码
查看>>
乐视视频 App 图标改为“欠 122 亿”,网友:我在别家分红包,却在你家随份子!...
查看>>
为何程序员总喜欢写技术博客,看完恍然大悟...
查看>>
假如计算机是中国人发明的,那代码应该这么写
查看>>
触目惊心:比特币到底消耗了多少能源?
查看>>
如何判断一家互联网公司要倒闭了?
查看>>
想快速上手机器学习?来看下这个 GitHub 项目!
查看>>
GitHub 标星 3.6k,一本开源的深度学习中文教程!
查看>>
9 款你不能错过的 JSON 工具
查看>>
就在昨天,全球 42 亿 IPv4 地址宣告耗尽!
查看>>