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

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

    1.3 中间表关联

1.1  code:

@Entity
public class article {
	@Id
	@GeneratedValue
   public Integer getArticleId() {
		return articleId;
	}
	.....
    @OneToOne(cascade=CascadeType.ALL)
	@PrimaryKeyJoinColumn
		public articleContent getContent() {
		return content;
	}
	......
}
@Entity
public class articleContent  {
    
	@Id
	@GeneratedValue
	public Integer getcId() {
		return cId;
	}
	....
}

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

1.2  code:

@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:

@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 分别生成两个外键具体参考等价建表语句:

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;

  

 

posted @ 2014-05-03 16:29  Rhythmk  阅读(184)  评论(0编辑  收藏  举报
Rhythmk 个人笔记