这个注解表示在父类上面的,用来标识父类。
基于代码复用和模型分离的思想,在项目开发中使用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 + "]" ;
}
}
|