• Rhythmk 学习 Hibernate 08


    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;
    

      

     

  • 相关阅读:
    【BZOJ2138】stone
    【ARC076F】 Exhausted
    [SDOI2018]战略游戏
    CF536D Tavas in Kansas
    [JSOI2018]战争
    ###学习《C++ Primer》- 5
    ###学习《C++ Primer》- 4
    ###Linux基础
    ###Linux基础
    ###Linux基础
  • 原文地址:https://www.cnblogs.com/rhythmK/p/3705259.html
Copyright © 2020-2023  润新知