我创建了一个名为 Person 的实体。它实现了生命周期接口。onLoad 方法设置部门属性。有时一个部门是未知的(== null)。
@Entity
@Table(name = "PERSON")
public class Person implements Lifecycle {
@Column(name = "NAME", length = 128, columnDefinition = "VARCHAR2(128)")
String name;
@Transient
Department department;
public void onLoad(Session s, Serializable id) {
// some logic resolving department
}
}
有没有办法使部门属性成为虚拟列(或类似的东西) - 从未在数据库中创建。
@Entity
@Table(name = "PERSON")
public class Person {
@Column(name = "NAME", length = 128, columnDefinition = "VARCHAR2(128)")
String name;
@Type(type = "DepartmentType") // UserType for resolving a department
//@Transcient
//@Column(insertable = false, updatable = false)
//@NotFound(action = NotFoundAction.IGNORE)
// ... don't have a clue
Department department;
}
我想有能力使用标准。
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.isNotNull("department"));
List<Person> list = criteria.list();
我了解 Criteria 在找到部门之前执行,因此无法解决属性“部门”。
我已经看到我可以从 UserType 的 nullSafeGet 中删除一行
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
rs.deleteRow();
}
但我不想从数据库中删除该行(它是只读的!)。
总结一下我的问题是:
1)是否可以创建一个虚拟列?
2)有没有更有效的方法来做到这一点?
Criteria criteria = session.createCriteria(Person.class);
// ... some restrictions ...
List<Person> list = criteria.list();
Iterator<EbamLogMessageEntity> it = list.iterator();
while(it.hasNext()) {
Person p = it.next();
Department d = resolveDepartment(p)
if(d == null) {
it.remove();
} else {
p.setDepartment(d);
}
}