JPA多表映射

JPA多表映射

一、单向多对一表映射

1.1、什么是单向一对多

就是多个学生有一个老师

1.2、使用JPA实现单向一对多

在学生类加一个老师对象,然后给老师对象

生成get,set方法加上@OneToMany ,@JoinColumn

1.3、@OneToMany,@JoinColumn

@OneToMany 表示一对多

@JoinColumn 设置外键名

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_TEACHER")
public class Teacher {
    private Integer id;
    private Integer age;
    private String teachCourse;
    private String name;

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Column(name = "TEACHER_COURSE")
    public String getTeachCourse() {
        return teachCourse;
    }

    public void setTeachCourse(String teachCourse) {
        this.teachCourse = teachCourse;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_STUDENT")
public class Student {
    private Integer id;
    private String lastName;
    private Boolean sex;
    private Integer age;
    private Teacher teacher;


    @JoinColumn(name = "TEACHER_ID")
    @ManyToOne(fetch = FetchType.LAZY)
    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    @Column(name = "LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

持久化对象,

@Test
public void testManyToOne(){

    Student student = new Student();
    student.setAge(12);
    student.setLastName("smallYellow");
    student.setSex(true);

    Student student1 = new Student();
    student1.setAge(18);
    student1.setLastName("smallGreen");
    student1.setSex(true);

    Teacher teacher = new Teacher();
    teacher.setAge(18);
    teacher.setTeachCourse("chinese");
    teacher.setName("ma");

    student.setTeacher(teacher);
    student1.setTeacher(teacher);

    entityManager.persist(teacher);
    entityManager.persist(student);
    entityManager.persist(student1);
}

@Test
public void ManyToOne(){
    Student student = entityManager.find(Student.class, 1);

    System.out.println(student.getLastName());

    System.out.println("-------------");
    System.out.println(student.getTeacher().getName());
}

二、单向一对多映射

2.1、什么是单向多对一

就是一个老师有多个学生

2.2、使用JPA实现单向一对多

在学生类加一个老师对象,然后给老师对象

生成get,set方法加上@OneToMany ,@JoinColumn

2.3、@OneToMany,@JoinColumn

@OneToMany 表示一对多

@JoinColumn name 设置外键名

2.4、cascade属性: 指定级联操作的行为(可多选)

1、CascadeType.PERSIST 级联新增(又称级联保存):
获取A对象里也同时也重新获取最新的B时的对象。即会重新查询数据库里的最新数据,并且,只有A类新增时,会级联B对象新增。若B对象在数据库存(跟新)在则抛异常(让B变为持久态),对应EntityManager的presist方法,调用JPA规范中的persist(),不适用于Hibernate的save()方法

2、 CascadeType.MERGE 级联合并(又称级联更新)
指A类新增或者变化,会级联B对象(新增或者变化) ,对应EntityManager的merge方法,调用JPA规范中merge()时,不适用于Hibernate的update()方法

3、CascadeType.REMOVE 级联删除
只有A类删除时,会级联删除B类,即在设置的那一端进行删除时,另一端才会级联删除,对应EntityManager的remove方法,调用JPA规范中的remove()时,适用于Hibernate的delete()方法

4、CascadeType.REFRESH 级联刷新
获取order(一或多)对象里也同时也重新获取最新的items(多)的对象,对应EntityManager的refresh(object),调用JPA规范中的refresh()时,适用于Hibernate的flush()方法

5、CascadeType.ALL
包含所有持久化方法

student 类

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_STUDENT")
public class Student {
    private Integer id;
    private String lastName;
    private Boolean sex;
    private Integer age;
//    private Teacher teacher;
//
//
//    @JoinColumn(name = "TEACHER_ID")
//    @ManyToOne(fetch = FetchType.LAZY)
//    public Teacher getTeacher() {
//        return teacher;
//    }
//
//    public void setTeacher(Teacher teacher) {
//        this.teacher = teacher;
//    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    @Column(name = "LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

teacher类

package com.kuang.pojo;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "JPA_TEACHER")
public class Teacher {
    private Integer id;
    private Integer age;
    private String teachCourse;
    private String name;
    private Set<Student> students=new HashSet<>();

    @OneToMany(cascade = {CascadeType.REMOVE})
    @JoinColumn(name = "Teacher_ID")
    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Column(name = "TEACHER_COURSE")

    public String getTeachCourse() {
        return teachCourse;
    }

    public void setTeachCourse(String teachCourse) {
        this.teachCourse = teachCourse;
    }

    public String getName() {
        return name;
    }

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

持久化

package com.kuang.test;

import com.kuang.pojo.Student;
import com.kuang.pojo.Teacher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestOneToMany {
    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private EntityTransaction transaction;

    @Before
    public void init() {
        entityManagerFactory = Persistence.createEntityManagerFactory("jpaHello");
        entityManager = entityManagerFactory.createEntityManager();
        transaction = entityManager.getTransaction();
        transaction.begin();
    }

    @After
    public void destroy() {
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void testPersistence() {
        Teacher teacher = new Teacher();
        teacher.setName("smailBlank");
        teacher.setTeachCourse("math");
        teacher.setAge(18);


        Student student = new Student();
        student.setSex(false);
        student.setLastName("BB");
        student.setAge(17);

        Student student1 = new Student();
        student1.setSex(true);
        student1.setLastName("cc");
        student1.setAge(37);
        teacher.getStudents().add(student);
        teacher.getStudents().add(student1);

        entityManager.persist(teacher);
        entityManager.persist(student);
        entityManager.persist(student1);

    }

    @Test
    public void testFind(){
        Teacher teacher = entityManager.find(Teacher.class, 1);

        System.out.println(teacher.getName());

        System.out.println(teacher.getStudents().size());
    }
}

三、双向一对多

3.1、什么是双向向一对多

就是一个老师有多个学生,对应的多个学生都有一个老师

3.2、使用JPA实现单向一对多

在学生类加一个老师对象,然后给老师对象加多个学生

生成get,set方法加上@OneToMany ,@JoinColumn ,@ManyToOne

3.3、@OneToMany,@JoinColumn

@OneToMany 表示一对多

@JoinColumn name 设置外键名

学生类

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_STUDENT")
public class Student {
    private Integer id;
    private String lastName;
    private Boolean sex;
    private Integer age;
    private Teacher teacher;


    @JoinColumn(name = "TEACHER_ID")
    @ManyToOne(fetch = FetchType.LAZY)
    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    @Column(name = "LAST_NAME")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

老师类

package com.kuang.pojo;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "JPA_TEACHER")
public class Teacher {
    private Integer id;
    private Integer age;
    private String teachCourse;
    private String name;
    private Set<Student> students=new HashSet<>();

    @OneToMany(cascade = {CascadeType.REMOVE},mappedBy = "teacher")
//    @JoinColumn(name = "Teacher_ID")
    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Column(name = "TEACHER_COURSE")

    public String getTeachCourse() {
        return teachCourse;
    }

    public void setTeachCourse(String teachCourse) {
        this.teachCourse = teachCourse;
    }

    public String getName() {
        return name;
    }

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

测试

package com.kuang.test;

import com.kuang.pojo.Student;
import com.kuang.pojo.Teacher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestOneToManyAndManyToOne {

    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private EntityTransaction transaction;

    @Before
    public void init(){
        entityManagerFactory= Persistence.createEntityManagerFactory("jpaHello");
        entityManager = entityManagerFactory.createEntityManager();
        transaction= entityManager.getTransaction();
        transaction.begin();
    }

    @After
    public void destroy(){
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void test(){
        Teacher teacher = new Teacher();
        teacher.setName("smailBlank");
        teacher.setTeachCourse("math");
        teacher.setAge(18);


        Student student = new Student();
        student.setSex(false);
        student.setLastName("BB");
        student.setAge(17);

        Student student1 = new Student();
        student1.setSex(true);
        student1.setLastName("cc");
        student1.setAge(37);
        teacher.getStudents().add(student);
        teacher.getStudents().add(student1);

        entityManager.persist(teacher);
        entityManager.persist(student);
        entityManager.persist(student1);
    }
}

四、双向一对一

4.1、什么是双向向一对一

就是一个班级有一个班长,一个班长都有一个班级

4.2、使用JPA实现单向一对多

在班级类加一个班长对象,然后给班长对象加班级对象

生成get,set方法加上@OneToOne ,@JoinColumn ,@OneToOne

4.3、@OneToOne,@JoinColumn

@OneToOne 表示一对一

@JoinColumn name 设置外键名

4.4、注意事项

双向映射需要加@mappedBy()给那个不需要维护双向关系

班级类

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_CLASS")
public class _Class {
    private Integer id;
    private String name;
    private int grade;
    private ClassMonitor classMonitor;

    @Id
    @GeneratedValue
    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 int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    @OneToOne(mappedBy = "_class")
    public ClassMonitor getClassMonitor() {
        return classMonitor;
    }

    public void setClassMonitor(ClassMonitor classMonitor) {
        this.classMonitor = classMonitor;
    }
}

班长类

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_CLASS_MONITOR")
public class ClassMonitor {
    private Integer id;
    private String name;
    private Integer age;
    private _Class _class;

    @Id
    @GeneratedValue
    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CLASS_ID",unique = true)
    public _Class get_class() {
        return _class;
    }

    public void set_class(_Class _class) {
        this._class = _class;
    }
}

测试

package com.kuang.test;


import com.kuang.pojo.ClassMonitor;
import com.kuang.pojo._Class;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestOneToOne {

    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private EntityTransaction transaction;

    @Before
    public void init(){
        entityManagerFactory= Persistence.createEntityManagerFactory("jpaHello");
        entityManager = entityManagerFactory.createEntityManager();
        transaction= entityManager.getTransaction();
        transaction.begin();
    }

    @After
    public void destroy(){
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void testFInd(){
        _Class aClass = entityManager.find(_Class.class, 1);
        System.out.println(aClass.getName());
        System.out.println(aClass.getClassMonitor().getName());
    }

    @Test
    public void testPersistence(){
        _Class aClass = new _Class();
        aClass.setGrade(3);
        aClass.setName("C-AA");
        _Class aClass1 = new _Class();
        aClass.setGrade(1);
        aClass.setName("C-BB");

        ClassMonitor classMonitor = new ClassMonitor();
        classMonitor.setAge(12);
        classMonitor.setName("m-aa");

        ClassMonitor classMonitor1 = new ClassMonitor();
        classMonitor1.setAge(18);
        classMonitor1.setName("m-BB");

        aClass.setClassMonitor(classMonitor);





        classMonitor.set_class(aClass);


;

        entityManager.persist(aClass);

        entityManager.persist(classMonitor);

    }

}

五、双向多对多

4.1、什么是双向向多对多

就是一个班级有一个班长,一个班长都有一个班级

4.2、使用JPA实现单向多对多

在班级类加一个班长对象,然后给班长对象加班级对象

生成get,set方法加上@ManyToMany ,@JoinTable

4.3、@ManyToMany,@JoinColumn

@OneToOne 表示一对一

@JoinTable name 设置之间表

/**
 * 使用@ManyTOMany 注解映射多对多关联关系
 * 使用 @JOin Table 来映射中间表
 * 1、name  指向中间表的名字
 * 2、joinColumn 映射当前的所在的表的中间表的外键
 * 2.1 name 指定外键列的列名
 * 2.2 referencedCOlumnName 指定列关联当前表的那一列
 * 2.3 inverseJoinColumns 映射关联的类所在中间表的外键
 * 3.inve
 */

4.4、注意事项

双向映射需要加@mappedBy()给那个对象不需要维护双向关系

物品类

package com.kuang.pojo;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "JPA_ITEM")
public class Item {
    private Integer id;
    private String name;
    private Set<Category> categories=new HashSet<>();

    @Id
    @GeneratedValue
    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;
    }

    @ManyToMany(mappedBy = "items")
    public Set<Category> getCategories() {
        return categories;
    }

    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }
}

种类

package com.kuang.pojo;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "JPA_CATEGERY")
public class Category {
    private Integer id;
    private String name;
    private Set<Item> items=new HashSet<>();

    @Id
    @GeneratedValue
    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;
    }


    @JoinTable(name = "JPA_ITEMS_CATEGORY",
             joinColumns = {@JoinColumn(name = "ITEM_ID",referencedColumnName = "ID")}
             ,inverseJoinColumns = {@JoinColumn(name = "CATEGORY",referencedColumnName = "ID")})
    @ManyToMany
    public Set<Item> getItems() {
        return items;
    }

    public void setItems(Set<Item> items) {
        this.items = items;
    }
}
package com.kuang.test;

import com.kuang.pojo.Category;
import com.kuang.pojo.Item;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestManyToMany {
    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private EntityTransaction transaction;

    @Before
    public void init(){
        entityManagerFactory= Persistence.createEntityManagerFactory("jpaHello");
        entityManager = entityManagerFactory.createEntityManager();
        transaction= entityManager.getTransaction();
        transaction.begin();
    }

    @After
    public void destroy(){
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void find(){
        Category category = entityManager.find(Category.class, 1);

        System.out.println(category.getName());

        System.out.println(category.getItems().size());



    }

    @Test
    public void persitence(){
        Category category = new Category();
        category.setName("苹果");

        Category category1 = new Category();
        category1.setName("小米");

        Item item = new Item();
        item.setName("ipone10");

        Item item1 = new Item();
        item1.setName("Mi11x");

        category.getItems().add(item);
        category.getItems().add(item1);

        category1.getItems().add(item);
        category1.getItems().add(item1);

        item.getCategories().add(category);
        item.getCategories().add(category1);

        item1.getCategories().add(category);
        item1.getCategories().add(category1);

        entityManager.persist(item);
        entityManager.persist(item1);
        entityManager.persist(category);
        entityManager.persist(category1);
    }
}

你可能感兴趣的:(学习记录,jpa,hibernate,object)