坚持@Transient

Persisting with @Transient

在我的 POJO 中我有这个:

@Transient
private int qtyMentee;

在我的 DAO 中我有这个查询:

public List<Employee> findQtyMentee(){
    TypedQuery<Employee> query = (TypedQuery<Employee>) em.createNativeQuery(
        "select *, count(mentor_id) as qtymentee from employee group by id order by qtymentee asc" , Employee.class);
    Collection<Employee> employee  = (Collection<Employee>) query.getResultList();
    return (List<Employee>) employee;
}

当我尝试获取 Qtymentee 时 returns 0。

注解@Transient在这种情况下是错误的?

如何获取此值并显示在我的应用程序中?

OBS:我正在使用 Eclipselink。

谢谢。

标有@Transient 的字段将不会保留。这意味着它们的值不存在于数据库中,并且在查询中使用它们将无效。来自规范:

This annotation specifies that the property or field is not persistent.

Javadoc link

@Transient 基本上就是 do not serialize me。所以 @Transient 会阻止你的字段被持久化。你应该删除它。

不支持您尝试执行的操作。 Transient 意味着它不是由 JPA 映射或处理的字段 - 它被排除在读取或从数据库中保留。在这种情况下,您正试图将计算出的数据推送到实体字段中,这会破坏由上下文维护的实体缓存。

希望您已将其映射为对象模型中的 1:M(比如 employee.mentees)和 M:1(比如 employee.mentor)。如果是这样,集合映射的简单大小将 return "mentee" 的数量,而不需要将值存储在某处。

如果您希望使用 JPQL(而不是使用 createNativeQuery 方法的 SQL)直接按值 return 排序列表:

List<Object[]> list = createQuery("Select e, size(e.mentees) as qtymentee from Employee e order by qtymentee asc").getResultList();

如果您没有使用引用映射映射 mentor_id 字段,您将需要求助于使用子查询,因为我认为您发布的 SQL 查询不会起作用。

如果必须将其放入数据对象中,可以使用此处描述的构造函数表达式http://docs.oracle.com/cd/E15523_01/apirefs.1111/e13946/ejb3_langref.html#ejb3_langref_constructor

它看起来像:

  createQuery("select new DAO(e.id, e.otherfield .., size(e.mentees)) from Employee e")