【发布时间】:2018-10-09 10:45:07
【问题描述】:
我正在通过使用在线教程和尝试可能的示例来自学 jpa,但现在我对如何使用表之间的关系有点困惑。我有 3 个具有 @Entity 注释的类,这意味着 jpa 将基于这些类创建表。我在 Student、Course、Booking 类中有 id 字段,它们将是各个表的主键。 我需要的帮助是,在 Booking 类中有 sid 和 cid 字段,我希望它们被引用,例如 sid(Student.java)=sid(Booking.java) & cid(Course.java)=cid(Booking.java ) 并且场景是每个学生可以一个或多个预订一门或多门课程。有人可以告诉我在我的代码中如何以及在哪里使用@OnetoOne、@OnetoMany、@ManytoMany、@ManytoOne。
Student.java
package com.testapp;
import java.util.List;
import javax.persistence.*;
@Entity
public class Student{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int sid;
private String name;
private int salary;
//Getters and Setters....
..
public Student() {
super();
}
public Student(int sid, String name, float salary) {
super();
this.sid = sid;
this.name = name;
this.salary = salary;
}
public Student(String name, float salary) {
super();
this.name = name;
this.salary = salary;
}
}
Course.java
package com.testapp;
import java.util.List;
import javax.persistence.*;
@Entity
public class Course {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int cid;
private String cname;
private int price;
//Getters and Setters....
..
public Course() {
super();
}
public Course(int cid, String cname, int price) {
super();
this.cid = cid;
this.cname = cname;
this.price = price;
}
public Course(String cname, int price) {
super();
this.cname = cname;
this.price = price;
}
}
Booking.java
package com.testapp;
import java.util.Set;
import javax.persistence.*;
@Entity
public class Booking {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int bid;
private String date;
private int sid;
private int cid;
//Getters and Setters....
..
public Booking() {
super();
}
public Booking(int bid, String date, int sid, int cid) {
super();
this.bid = bid;
this.date= date;
this.sid = sid;
this.cid = cid;
}
public Booking(String date, int sid, int cid) {
super();
this.date = date;
this.sid = sid;
this.cid = cid;
}
}
谢谢你..
【问题讨论】:
-
我相信您不需要创建第三个预订表,就好像您定义了学生和课程之间的多对多关系,那么这应该足以满足您的要求。
-
但是,如果您想为每个预订关联一个日期,则需要定义一对多和多对一关系。
-
任何 JPA 教程都会告诉您如何使用关系(就像任何面向对象的编程书籍一样)。而不是仅仅在你的类中转储随机整数(这不是关系)
标签: java database hibernate jpa spring-data-jpa