光辉飞翔

导航

 

@MappedSuperclass

用在父类上面。当这个类肯定是父类时,加此标注。如果改成@Entity,则继承后,多个类继承,只会生成一个表,而不是多个继承,生成多个表。

例子:

 

 

@MappedSuperclass的用法 用在实体的继承过程中的父类上;

父类Cat Java代码 package com.xj.model;    import javax.persistence.GeneratedValue;  import javax.persistence.Id;  import javax.persistence.MappedSuperclass;    @MappedSuperclass  public class Cat {      private Long id;      private String name;      @Id      @GeneratedValue      public Long getId() {          return id;       }      public void setId(Long id) {          this.id = id;       }      public String getName() {          return name;       }      public void setName(String name) {          this.name = name;       } 

package com.xj.model;

import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass;

@MappedSuperclass public class Cat { private Long id; private String name; @Id @GeneratedValue public Long getId() {   return id; } public void setId(Long id) {   this.id = id; } public String getName() {   return name; } public void setName(String name) {   this.name = name; } }

子类1 BeijingCat Java代码 package com.xj.model;    import javax.persistence.Entity;  import javax.persistence.Table;    @Entity  @Table(name="t_beijingcat")  public class BeijingCat extends Cat {      private String beijing;        public String getBeijing() {          return beijing;       }        public void setBeijing(String beijing) {          this.beijing = beijing;       }   

package com.xj.model;

import javax.persistence.Entity; import javax.persistence.Table;

@Entity @Table(name="t_beijingcat") public class BeijingCat extends Cat { private String beijing;

public String getBeijing() {   return beijing; }

public void setBeijing(String beijing) {   this.beijing = beijing; }

}

子类2 ShanghaiCat Java代码 package com.xj.model;    import javax.persistence.Entity;  import javax.persistence.Table;    @Entity  @Table(name="t_shanghaiCat")  public class ShanghaiCat extends Cat {      private String shanghai;        public String getShanghai() {          return shanghai;       }        public void setShanghai(String shanghai) {          this.shanghai = shanghai;       } 

package com.xj.model;

import javax.persistence.Entity; import javax.persistence.Table;

@Entity @Table(name="t_shanghaiCat") public class ShanghaiCat extends Cat { private String shanghai;

public String getShanghai() {   return shanghai; }

public void setShanghai(String shanghai) {   this.shanghai = shanghai; } }

结果生成 两张表t_beijingcat、 t_shanghaicat

如果不用@MappedSuperclass 而用@Entity替换的话,只会生成一张cat表,字段有:id,name,shanghaicat,bejingcat

posted on 2012-08-20 11:09  光辉飞翔  阅读(4031)  评论(0编辑  收藏  举报