首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Hibernate和JPA触发意外查询

使用Hibernate和JPA触发意外查询
EN

Stack Overflow用户
提问于 2015-07-25 11:10:15
回答 2查看 1.2K关注 0票数 0

我编写了从DB获取数据的代码,但它也触发了一个意外的查询:

代码语言:javascript
运行
复制
@SuppressWarnings("unchecked")
    @Transactional
    public List<Job> getAppliedPositionsById(Long userId) {
//      String currentDate = SQLDateFormator.getCurrentDateInSqlFormat();
        String strQuery = "from Job x left join x.applications a where a.applicant.id = :userId";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("userId", userId);
        return query.getResultList();
    }

return query.getResultList();上,它会触发两个查询。由于第二个查询,我得到了异常。

两个查询

冬眠:

代码语言:javascript
运行
复制
    select
        job0_.id as id1_5_0_,
        applicatio1_.id as id1_1_1_,
        job0_.close_date as close_da2_5_0_,
        job0_.committee_chair_id as committe6_5_0_,
        job0_.description as descript3_5_0_,
        job0_.publish_date as publish_4_5_0_,
        job0_.title as title5_5_0_,
        applicatio1_.applicant_id as applican6_1_1_,
        applicatio1_.current_job_institution as current_2_1_1_,
        applicatio1_.current_job_title as current_3_1_1_,
        applicatio1_.current_job_year as current_4_1_1_,
        applicatio1_.cv_id as cv_id7_1_1_,
        applicatio1_.job_id as job_id8_1_1_,
        applicatio1_.research_statement_id as research9_1_1_,
        applicatio1_.submit_date as submit_d5_1_1_,
        applicatio1_.teaching_statement_id as teachin10_1_1_ 
    from
        jobs job0_ 
    left outer join
        applications applicatio1_ 
            on job0_.id=applicatio1_.job_id 
    where
        applicatio1_.applicant_id=?

冬眠:

代码语言:javascript
运行
复制
    select
        user0_.id as id1_8_0_,
        user0_.address as address2_8_0_,
        user0_.email as email3_8_0_,
        user0_.first_name as first_na4_8_0_,
        user0_.last_name as last_nam5_8_0_,
        user0_.password as password6_8_0_,
        user0_.phone as phone7_8_0_ 
    from
        users user0_ 
    where
        user0_.id=?

关于Users表的第二个查询完全没有必要。

Job实体

代码语言:javascript
运行
复制
   @Id
    @GeneratedValue
    private Long id;

    private String title;

    private String description;

    @Column(name = "publish_date")
    private Date publishDate;

    @Column(name = "close_date")
    private Date closeDate;

    @ManyToOne
    @JoinColumn(name = "committee_chair_id")
    private User committeeChair;

    @ManyToMany
    @JoinTable(name = "job_committee_members",
        joinColumns = @JoinColumn(name = "job_id") ,
        inverseJoinColumns = @JoinColumn(name = "user_id") )
    @OrderBy("lastName asc")
    private List<User> committeeMembers;

    @OneToMany(mappedBy = "job")
    @OrderBy("date asc")
    private List<Application> applications;
}

Application实体:

代码语言:javascript
运行
复制
 @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private Job job;

    @ManyToOne
    private User applicant;

    @Column(name = "submit_date")
    private Date submitDate;

    @Column(name = "current_job_title")
    private String currentJobTitle;

    @Column(name = "current_job_institution")
    private String currentJobInstitution;

    @Column(name = "current_job_year")
    private Integer currentJobYear;

    @ElementCollection
    @CollectionTable(name = "application_degrees",
        joinColumns = @JoinColumn(name = "application_id") )
    @OrderBy("year desc")
    private List<Degree> degrees;

    @OneToOne
    private File cv;

    @OneToOne
    @JoinColumn(name = "research_statement_id")
    private File researchStatement;

    @OneToOne
    @JoinColumn(name = "teaching_statement_id")
    private File teachingStatement;

    @OneToMany(mappedBy = "application",
        cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    @OrderColumn(name = "round_index")
    private List<Round> rounds;
}

User实体:

代码语言:javascript
运行
复制
@Id
    @GeneratedValue
    private Long id;

    @Column(unique = true, nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    private String address;

    private String phone;

    @OneToMany(mappedBy = "applicant")
    @OrderBy("id desc")
    private List<Application> applications;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-25 11:47:22

在JPA2.0规范中,默认设置如下:

OneToMany:懒惰 ManyToOne:热切 ManyToMany:懒惰 OneToOne:热切

在应用程序类中

代码语言:javascript
运行
复制
@ManyToOne
private User applicant;

如果你把它换成懒惰的话

代码语言:javascript
运行
复制
@ManyToOne(fetch = FetchType.LAZY)

它应该按你想的方式工作。

票数 1
EN

Stack Overflow用户

发布于 2015-07-25 15:25:03

正如luksch所指出的,您的模型为用户定义了一个@ManyToOne关系,默认情况下,每次加载作业实例(或模型中的应用程序实例)时,都会急切地获取。然而,切换它FetchType.LAZY现在可能会产生预期的结果。使用oneToOne或manyToOne,hibernate将不得不进行额外的查询,即使它很懒。只有当您指定关系的optional=false属性和FetchType.LAZY时,它才会自动将代理对象设置为用户属性值。这是因为Hibernate在检查DB之前无法知道用户属性是否存在或为null。根据您的模型,一个更合适的解决方案是更新查询,以便在一个查询中获取用户对象,如下所示:

代码语言:javascript
运行
复制
String strQuery = "from Job x left join fetch x.committeeChair u left join x.applications a where a.applicant.id = :userId"

重要的部分是左连接获取x.committeeChair u,它告诉hibernate添加一个额外的连接并获取相关的对象。

这修复了使用JPQL获取作业实例时的行为。如果尝试通过id通过EntityManager.find方法加载单个作业实例。它仍然会为用户committeeChair生成一个额外的查询。您的加载策略可以通过使用Hibernate特定的(还不是JPA标准)获取模式进一步优化--请注意,获取模式可能会禁用可能不需要的延迟加载。我建议您首先决定需要加载哪些数据,始终存在哪些数据,并在此基础上优化查询。通常,额外的查询比在一个查询中加载整个实体图更好。祝好运

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31625845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档