工作中遇到hibernate映射的一些问题,这里总结一下
(特别是测试时,许多数据并不能有效关联。所以@NotFound 很重要)
一,假设有2张表user,company
我们知道,一个用户属于一个公司。那么我们这么创建Model
//用户 public class User { private int id; private String name; private int companyid //sub table private Company company; @Where(clause="IsValid=1") @OneToOne(fetch= FetchType.EAGER,optional = true) @NotFound(action= NotFoundAction.IGNORE) @JoinColumn(name = "companyid", referencedColumnName = "companyid",insertable = false, updatable = false) public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } } //公司 public class Company { private int companyid; private int isValid; //是否有效 }
二 , 解释一下
@Where(clause="IsValid=1") 设定只查询IsValid=1的信息
@OneToOne(fetch= FetchType.EAGER,optional = true) FetchType.EAGER 及时加载,optional = true 是否必须有值
@NotFound(action= NotFoundAction.IGNORE) 忽略没有关联的外键
@JoinColumn(name = "inboundOrderUUID", referencedColumnName = "inboundOrderUUID",insertable = false, updatable = false)
name:本类的关联id referencedColumnName:关联项的id
PS:Dao使用@Query注解,也会查询到关联对象。