【问题标题】:Why do I need to use mappedBy Annotation?为什么我需要使用 mappedBy Annotation?
【发布时间】:2015-02-05 18:40:32
【问题描述】:

鉴于这个image,我想知道我是否应该在其他文件中使用mappedBy 的同时使用JoinColumn。或者,如果我不需要使用mappedBy,那就可以了!

谁能告诉我为什么我们需要使用mappedBy

Employee.java

@Id
@GeneratedValue
@Column(name="employee_id")
private Long employeeId;

@Column(name="firstname")
private String firstname;

@Column(name="lastname")
private String lastname;

@Column(name="birth_date")
private Date birthDate;

@Column(name="cell_phone")
private String cellphone;

@ManyToOne
@JoinColumn(name="department_id")
private Department department;

public Employee() {

}

public Employee(String firstname, String lastname, String phone) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.birthDate = new Date(System.currentTimeMillis());
    this.cellphone = phone;
}

// Getter and Setter methods

Department.java

@Id
@GeneratedValue
@Column(name="DEPARTMENT_ID")
private Long departmentId;

@Column(name="DEPT_NAME")
private String departmentName;

@OneToMany(mappedBy="department")
private Set<employee> employees;

// Getter and Setter methods

【问题讨论】:

    标签: java hibernate spring-mvc jpa


    【解决方案1】:

    为什么需要使用“mappedBy”?你用它来定义一个关系是双向的,并指定关系的另一边是什么(对于 1-1,你在 FK 一侧指定它,对于 1-N,你在 Collection 一侧指定它)。因此,如果您的关系是单向的,则不必“必须”指定它。阅读任何一半像样的 JPA 文档都会告诉您这一点;你的实现文档没有告诉你这一点吗?

    【讨论】:

    • 有没有想过实际尝试一些东西?这个问题得到了回答。
    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2019-06-09
    • 2011-07-05
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多