java - JPA nativeQuery 返回缓存的 resultList

标签 java mysql hibernate jpa nativequery

我有以下类(class):

公司类别:

public class Company {
    @JoinTable(name = "company_employee", joinColumns = @JoinColumn(name = "company_id") , inverseJoinColumns = @JoinColumn(name = "employee_id") )
    @ManyToMany(fetch = FetchType.LAZY)
    private Set<Employee> employees;

    @Column(name = "score")
    private BigDecimal score;
}

和 Employee.class

public class Employee {
         @ManyToMany(fetch = FetchType.EAGER, mappedBy="employees")
         private Set<Company> companies;
}

Company 的 Score 列在数据库中始终为空,并且从未通过 dao 更新,因为还有其他表包含每个唯一的 Company-Employee 对的分数。 我需要 Score 的值,仅适用于通过 id 获取 Employee 的情况,因此这种情况下 Set 中的所有 Company 实例都应包含分数,因此我将在获取 Employee 时获得 Employee-Company 分数对。 我有以下代码来实现这一点:

public Employee get(Long id) {
    Employee emp = (Employee) dao.find(id);
    List<Company> compList = compnanyService.getByEmpId(id);
    Set<Company> compSet = new HashSet<Company>(compList);
    emp.setCompanies(compSet);
    return emp;
}

而Company Dao包含方法:

public List<Company> getByEmpId(Long id) {
        final Query query = this.entityManager.createNativeQuery("select company.comp_id, ...some other fields, score.score from company join score on company.company_id=score.company_id where score.employee_id=:employee_id",
                Company.class);
        query.setParameter("employee_id", id);
        List<Company> comps = query.getResultList();
        return comps;
}

问题是 getByEmpId(id)给出 ResultList哪里company.score虽然在数据库中执行但它不为空,但为空。

我怀疑存在一些缓存干预,因此我尝试从 native 查询中删除一些列,并且它应该在映射时调用带有“未找到列”(或类似)消息的异常,但此方法仍然给出List<Company>尽管 Hibernate 会在控制台中打印出我的 native 查询以及我所做的所有更改,但所有字段都已就位。 我在这里做错了什么以及如何实现我需要的?谢谢。

最佳答案

它可能与一级缓存相关,在使用 native SQL 查询时可能会不同步。来自 here :

If you bypass JPA and execute DML directly on the database, either through native SQL queries, JDBC, or JPQL UPDATE or DELETE queries, then the database can be out of synch with the 1st level cache. If you had accessed objects before executing the DML, they will have the old state and not include the changes. Depending on what you are doing this may be ok, otherwise you may want to refresh the affected objects from the database.

因此,您可以尝试使用 EntityManager 中的 refresh 方法。

关于java - JPA nativeQuery 返回缓存的 resultList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484203/

相关文章:

java - Facebook API 是否允许搜索帐户中的个人资料、网络、雇主、学校信息?

mysql - 选择接下来 24 小时的工作

mysql - REGEXP "and"运算符

java - 如何使用 Hibernate 将 ORM 转换为其子类?

java - 尽管很忙,但我的后台服务被杀死并等待了很长时间才重新启动

java - 如何使用java从SVN仓库中获取所有文件和目录

php单例数据库连接,这段代码是不好的做法吗?

mysql - 如何使用hibernate交换数据库中的id

java - Liquibase Hibernate 插件不工作

java - JSF、数据表和 onRowClick