版权声明:自由转载-非商用-保持署名,觉得此文有用的,不嫌麻烦的话,就留个言,或者点个赞吧,如果觉得文章有错误,望您指点。QQ交流群:865061230 https://blog.csdn.net/Sirius_hly/article/details/82907907
映射关系思维导图
清晰思维导图分享地址为:JPA思维导图
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.实体类
实体类有作者,书籍,和作者所对应的出版的书籍
作者类
@Entity
public 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<Book> books;
}
书籍类
@Entity
public 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<Book> 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类
@Entity
public class Boss {
@Id
@GeneratedValue
private int id;
private String name;
//多方设置指向一方的主键
//mappedBy:Boss类为多方关系维护方,负责数据库外键boss_id的更新
@OneToMany(cascade = CascadeType.ALL,mappedBy = "boss")
private Collection<Employee> employees = new ArrayList<Employee>();
}
员工类
@Entity
public 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<Employee> collection = new ArrayList<Employee>();
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类
@Entity
public class People {
@Id
@GeneratedValue
private int id;
private String name;
}
Car类
@Entity
public 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类
@Entity
public class Course {
@Id
@GeneratedValue
private int id;
private String courseName;
}
Student类
@Entity
public 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<Course> 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<Course> 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类
@Entity
public 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> classes = new ArrayList<Classes>();
}
Classes类
@Entity
public class Classes {
@Id
@GeneratedValue
private int id ;
private String name;
//mapperBy为Teacher的Classes属性
@ManyToMany(mappedBy = "classes",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Collection<Teacher> teachers = new ArrayList<Teacher>();
}
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<Teacher> teachers = new ArrayList<>();
Collection<Classes> 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();
}
代码及地址
完整代码在笔者的github,欢迎访问。