为什么我可以在id不存在时更新/创建引用对象

时间:2018-04-23 09:02:22

标签: java hibernate

我有两个带引用ID的表。当id不存在时,我可以更新/创建部门。我认为我严重束缚了我的身份。但我做错了什么,我不知道。请解释我做错了什么。

CREATE TABLE FACULTY (
ID SERIAL PRIMARY KEY,  
NAME VARCHAR(20) NOT NULL );


CREATE TABLE DEPARTMENT (   
ID SERIAL PRIMARY KEY,   
NAME VARCHAR (20) NOT NULL,   
FACULTY_ID INTEGER REFERENCES FACULTY(ID) ON DELETE SET NULL );

教师表

@Entity
@Table(name = "Faculty")
public class Faculty implements Serializable {

    private Long id;
    private String name;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

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

   // getters and setters of name

部门表

@Entity 
@Table(name = "department") 
public class Department implements Serializable {

        private Long id;
        @Column(name = "name")
        private String name;

        private Faculty facultyId;

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        public Long getId() {
            return id;
        }

        @ManyToOne
        @JoinColumn(name = "faculty_id")
        public Faculty getFacultyId() {
            return facultyId;
        }

        public void setFacultyId(Faculty facultyId) {
            this.facultyId = facultyId;
        }

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

       // getters and setters of name

1 个答案:

答案 0 :(得分:0)

根据OneToMany的关系,一个部门可以有很多院系。

因此,在您的关系中,faculty表将引用departmentID。在您的情况下,如果deptfacultyId作为参考,那么该ID将有多个值,因为1个部门中有许多院系。

因此,请在departmentID表中保留Faculty作为参考。这样,1个教师将拥有1个departmentID。

CREATE TABLE DEPARTMENT (   
ID SERIAL PRIMARY KEY,   
NAME VARCHAR (20) NOT NULL,   
); 



CREATE TABLE FACULTY (
ID SERIAL PRIMARY KEY,  
NAME VARCHAR(20) NOT NULL
DEPARTMENT_ID INTEGER REFERENCES DEPARTMENT(ID) ON DELETE SET NULL );