本文共 11723 字,大约阅读时间需要 39 分钟。
清晰思维导图分享地址为:
一个实体A与另一个实体B之间存在关系,通过A可以获得B,通过B不能获得A。
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;
添加文章类和用户类
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是所对应的外键。
@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.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;
实体类有作者,书籍,和作者所对应的出版的书籍
作者类
@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 Collectionbooks;}
书籍类
@Entitypublic class Book { @Id @GeneratedValue private int id; private String bookName;}
出版类
public class Publish { private int authorId; private int bookId;}
/** * 双向一对多关系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"); Collectioncollection = new ArrayList<>(); collection.add(book1); collection.add(book2); author.setBooks(collection); em.persist(author); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }
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;
BOSS类
@Entitypublic class Boss { @Id @GeneratedValue private int id; private String name; //多方设置指向一方的主键 //mappedBy:Boss类为多方关系维护方,负责数据库外键boss_id的更新 @OneToMany(cascade = CascadeType.ALL,mappedBy = "boss") private Collectionemployees = new ArrayList ();}
员工类
@Entitypublic class Employee { @Id @GeneratedValue private int id; private String name; //todo 外键为null @ManyToOne @JoinColumn(name = "bossId") private Boss boss;}
/** * 双向一对多关系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"); Collectioncollection = 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(); }
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;
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
/** * 单向多对一关系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(); }
从多方A可以获得另外的多方B;从B不需要获得A
学生,课程,选课表
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;
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 Collectioncourses;}
选课类
public class SelectCourse { private int studentId; private int courseId;}
/** * 单向多对多关系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("数据库"); Collectioncourses = new ArrayList<>(); courses.add(course1); courses.add(course2); student.setCourses(courses); em.persist(student); em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }
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;
教师,班级,教师班级关系类
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 Collectionclasses = 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 Collectionteachers = new ArrayList ();}
Teaching类
public class Teaching { //命名不是teacher_id格式需要在teacher类中@JoinTable里声明 private int classId; private int teacherId;}
/** * 双向多对多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"); Collectionteachers = 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(); }
完整代码在笔者的,欢迎访问。