@MappedSuperclass的用法


這個注解表示在父類上面的,用來標識父類。

基於代碼復用和模型分離的思想,在項目開發中使用JPA的@MappedSuperclass注解將實體類的多個屬性分別封裝到不同的非實體類中。例如,數據庫表中都需要id來表示編號,id是這些映射實體類的通用的屬性,交給jpa統一生成主鍵id編號,那么使用一個父類來封裝這些通用屬性,並用@MappedSuperclas標識。

注意:

1.標注為@MappedSuperclass的類將不是一個完整的實體類,他將不會映射到數據庫表,但是他的屬性都將映射到其子類的數據庫字段中。

2.標注為@MappedSuperclass的類不能再標注@Entity或@Table注解,也無需實現序列化接口

例子: IdEntity封裝了實體類的id屬性

public abstract class IdEntity {  
    protected Integer id;  
    public abstract Integer getId();  
    public abstract void setId(Integer id);  
      
}  

  


 
@MappedSuperclass  
public abstract class BaseEntity extends IdEntity {  
  
    @Id  
    @GeneratedValue  
    @Column(length=20)    
    public Integer getId() {  
        return this.id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
      
}  

  

 


 
@Entity  
@Table(name="yyw_user")  
@Cache(usage= org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)  
public class User extends BaseEntity {  
    @Column(length=20,nullable=false)  
    private String name;  
    @Column(length=20,nullable=true)  
    private String password;  
      
    public User(){}  
    public User(String name, String password) {  
        super();  
        this.name = name;  
        this.password = password;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
      
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  
    @Override  
    public String toString() {  
        return "User [name=" + name + ", id=" + id + ", password=" + password  
                + "]";  
    }  
}  

  

 


 
@Entity  
@Table(name="yyw_subjects")  
@Cache(usage= org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)  
public class Subject extends BaseEntity {  
      
    @Column(length=20,nullable=false)  
    private String content;  
    public Subject(){}  
    public Subject(String content){  
        this.content = content;  
    }  
    public String getContent() {  
        return content;  
    }  
    public void setContent(String content) {  
        this.content = content;  
    }  
    @Override  
    public String toString() {  
        return "Subject [id=" + id + ", content=" + content + "]";  
    }  
}  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM