在hibernate中关系的所有者方

时间:2018-06-02 03:13:45

标签: hibernate jpa

我正在阅读article以澄清我对关系所有者方面的疑虑,但这让我更加困惑。他们使用以下作为例子:

Sql scheme

CREATE TABLE `authors` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `biographies` (
  `author_id` int(6) NOT NULL,
  `information` varchar(100) NOT NULL,
  KEY `author_bio` (`author_id`),
  CONSTRAINT `author_bio` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在java中的映射

@Entity
@Table(name="authors")
public class Author {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @OneToOne(mappedBy="author", cascade=CascadeType.ALL)
    private Biography biography;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Biography getBiography() {
        return biography;
    }

    public void setBiography(Biography biography) {
        this.biography = biography;
    }

}

import javax.persistence.*;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="biographies")
public class Biography {

    @Id
    @Column(name="author_id")
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", 
    parameters=@Parameter(name="property", value="author"))
    private Integer authorId;

    private String information;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Author author;

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public Integer getAuthorId() {
        return authorId;
    }

    public void setAuthorId(Integer authorId) {
        this.authorId = authorId;
    }

    public String getInformation() {
        return information;
    }

    public void setInformation(String information) {
        this.information = information;
    }   
}

我想解决以下问题:

  1. 为什么关系的所有者方是Author类,如果Author类具有mappedBy属性,这表明它是关系的反面,即非所有者?

  2. 如果双方使用cascade-all属性,作者或传记类被设置为关系的所有者方面有什么区别?

  3. 记住提供的SQL模型。为什么在OneToOne单向关系中,如果我们看到传记表具有 authors 表的外键,则可以选择Author作为所有者方,这意味着当将数据库的表映射到java类时,Biography类成为所有者,因为表传记具有表 authors 的外键。

0 个答案:

没有答案