Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

1、一对一 (One to One)
    共三种情况:
     1.1 主键共享
    1.2 外键共享

    1.3 中间表关联

1.1  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Entity
public class article {
    @Id
    @GeneratedValue
   public Integer getArticleId() {
        return articleId;
    }
    .....
    @OneToOne(cascade=CascadeType.ALL)
    @PrimaryKeyJoinColumn
        public articleContent getContent() {
        return content;
    }
    ......
}
1
2
3
4
5
6
7
8
9
10
@Entity
public class articleContent  {
     
    @Id
    @GeneratedValue
    public Integer getcId() {
        return cId;
    }
    ....
}

  执行保存 生成两张无外键的独立表

1.2  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Entity
public class article {
     
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="cid_fk")
        public articleContent getContent() {
        return content;
    }
     
}
 
@Entity
public class articleContent  {
     
    @OneToOne(mappedBy="articleContent")
    public article ArticleEntity;
}

  执行保存,生成两张表,同时article生成一个cid_fk字段 关联 articleContent主键ID

1.3  code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Entity
public class article {
    @Id
    @GeneratedValue
   public Integer getArticleId() {
        return articleId;
    }
 
    @OneToOne(cascade=CascadeType.ALL)
    @JoinTable(name="article_content",
          joinColumns=@JoinColumn(name="aid"),
          inverseJoinColumns=@JoinColumn(name="aid_fk"))
        public articleContent getContent() {
        return content;
    }
    ......
}

  生成三张表 分别为:article,article_content,articlecontent  其中 article_content 分别生成两个外键具体参考等价建表语句:

1
2
3
4
5
6
7
8
CREATE TABLE `article_content` (
  `aid_fk` int(11) DEFAULT NULL,
  `aid` int(11) NOT NULL,
  PRIMARY KEY (`aid`),
  KEY `FK_7pgn2vn8r1lpswmh5v2ix667s` (`aid_fk`),
  CONSTRAINT `FK_ebfc4cs1sishg6u8kwpvgqqj9` FOREIGN KEY (`aid`) REFERENCES `article` (`articleId`),
  CONSTRAINT `FK_7pgn2vn8r1lpswmh5v2ix667s` FOREIGN KEY (`aid_fk`) REFERENCES `articlecontent` (`cId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  

 

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解,布布扣,bubuko.com

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

上一篇:Linux 标准目录结构


下一篇:linux根分区扩容