Hibernate关系映射总结

其实这些东东完全可以参考帮助文档;这里只是总结下。
》》》一对一映射
妻子类
	@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 {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值