其实这些东东完全可以参考帮助文档;这里只是总结下。
》》》一对一映射
妻子类
丈夫类
》》》一对多映射
班级类
学生类
》》》多对多映射
用户类
角色类
》》》联合主键映射
有三种方式 这里只是其中一种。
主键类 (实现Serializable接口,重写hashCode、equals方法)
用到主键类的学生类
》》》组件映射
组件类
用到组件类的类
》》》外键映射
学生类
》》》继承映射
若把父类@MappedSuperclass换成@Entity则只生成一张表 且包含所有子类信息!!
父类Cat类
子类1
子类2
》》》一对一映射
妻子类
@OneToOne
@JoinColumn(name="husbandID")
public Husband getHusband() {
return husband;
}
丈夫类
@OneToOne(cascade=CascadeType.ALL,mappedBy="husband")
public Wife getWife() {
return wife;
}
》》》一对多映射
班级类
@OneToMany(mappedBy="class1",fetch=FetchType.LAZY)
public Set<Student> getStudents() {
return students;
}
学生类
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="classID")
public Class1 getClass1() {
return class1;
}
》》》多对多映射
用户类
@ManyToMany(targetEntity=com.xj.model.Role.class,
cascade=CascadeType.PERSIST)
@JoinTable(name="t_user_role",
joinColumns=@JoinColumn(name="userID"),
inverseJoinColumns=@JoinColumn(name="roleID"))
public Set<Role> getRoles() {
return roles;
}
角色类
@ManyToMany(targetEntity=com.xj.model.User.class,
mappedBy="roles")
public Set<User> getUsers() {
return users;
}
》》》联合主键映射
有三种方式 这里只是其中一种。
主键类 (实现Serializable接口,重写hashCode、equals方法)
public class NamePK implements Serializable{
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final NamePK other = (NamePK) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
}
用到主键类的学生类
@IdClass(NamePK.class)
@Entity
@Table(name="t_student")
public class Student {
......
@Id
public String getFirstName() {
return firstName;
}
@Id
public String getLastName() {
return lastName;
}
}
》》》组件映射
组件类
@Embeddable
public class NamePK implements Serializable{
用到组件类的类
private NamePK namePK;
》》》外键映射
学生类
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="classID")
public Class1 getClass1() {
return class1;
}
》》》继承映射
若把父类@MappedSuperclass换成@Entity则只生成一张表 且包含所有子类信息!!
父类Cat类
@MappedSuperclass
public class Cat {}
子类1
@Entity
@Table(name="t_beijingcat")
public class BeijingCat extends Cat {
子类2
@Entity
@Table(name="t_shanghaiCat")
public class BeijingCat extends Cat {