@MappedSuperclass的用法

这个注解表示在父类上面的,用来标识父类。

基于代码复用和模型分离的思想,在项目开发中使用JPA的@MappedSuperclass注解将实体类的多个属性分别封装到不同的非实体类中。例如,数据库表中都需要id来表示编号,id是这些映射实体类的通用的属性,交给jpa统一生成主键id编号,那么使用一个父类来封装这些通用属性,并用@MappedSuperclas标识。

注意:

1.标注为@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,但是他的属性都将映射到其子类的数据库字段中。

2.标注为@MappedSuperclass的类不能再标注@Entity或@Table注解,也无需实现序列化接口。

例子: IdEntity封装了实体类的id属性

1

2

3

4

5

6

public abstract class IdEntity { 

    protected Integer id; 

    public abstract Integer getId(); 

    public abstract void setId(Integer id); 

       

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

    

       

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

@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 

                "]"

    

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

@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 + "]"

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值