JPA选择,什么应该是懒惰加载,什么时候没必要

时间:2013-08-09 15:26:23

标签: sql performance select jpa lazy-loading

我有一个映射到这个类的表:

@Entity(name = "status_history")
    @Table
    public class StatusChange implements Comparable<StatusChange> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "when_")
    @Temporal(TemporalType.TIMESTAMP)
    private Date when;
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "ordering_id")
    private Ordering ordering;
    private Short status;
    ...



@Override
public int hashCode() {
    return id.intValue();
}

@Override
public boolean equals(Object o) {
    if (o instanceof StatusChange) {
        StatusChange sc = (StatusChange) o;
        if (id == null) {
            return false;
        }
        return id.equals(sc.getId());
    }
    return false;
}
    ...

有5006行。为什么记录显示,当我执行此查询时:

 Query query = em.createQuery("SELECT DISTINCT sh FROM status_history sh");
 return query.getResultList();

日志记录显示JPA还提取了已编译的类:

[EL Fine]: sql: 2013-08-09 17:02:52.631--ServerSession(27039955)--Connection(12972016)--Thread(Thread[main,5,main])--SELECT ID, TYPE, anniversary_newspapers, anniversary_newspapers_type, AUTHOR, copy_color, copy_format, decorated_folder, decorated_folder_note, delivery_type, publishing_description, SIGNATURE, TITLE, USAGE, work_amount, work_amount_desc, work_type, year_, BARCODE, comment_, denial_reason, EXHIBITION, exhibition_name, further_processing, LZA, no_new_scans, ONLINE, RESTORATION, SMALL, URGENT FROM ordered_object WHERE (ID = ?)
    bind => [54]
[EL Fine]: sql: 2013-08-09 17:02:52.632--ServerSession(27039955)--Connection(12972016)--Thread(Thread[main,5,main])--SELECT ID, TYPE, cancel_comment, claim_comment, COMMUNICATION, EDITOR, internal_id, LOCATION, STATUS, YEAR, yearly_number, billing_contact_id, oo_id, orderer_id, accumulated, customer_created, estimated_price, no_barcode, no_object, accumulated_id FROM ORDERING WHERE (oo_id = ?)
    bind => [54]
[EL Fine]: sql: 2013-08-09 17:02:52.634--ServerSession(27039955)--Connection(12972016)--Thread(Thread[main,5,main])--SELECT ID, _comment, control_finished, CONTROLLER, date_of_entry, empty_pages, scan_finished, scan_method1, scan_method2, scan_operator, SCANNER, SENDER, thumbnail_number, total_pages, oo_id FROM SCAN_INFO WHERE (oo_id = ?)
    bind => [54]
[EL Fine]: sql: 2013-08-09 17:02:52.635--ServerSession(27039955)--Connection(12972016)--Thread(Thread[main,5,main])--SELECT ID, onb_employee, contact_id FROM ORDERER WHERE (ID = ?)
    bind => [54]

,查询需要30秒。我在这里失踪了什么? 非常感谢!

1 个答案:

答案 0 :(得分:0)

EclipseLink要求启用编织以允许在OneToOne和ManyToOne关系上使用延迟,否则它只是一个提示 文档http://www.eclipse.org/eclipselink/documentation/2.4/concepts/app_dev007.htm包含有关使用EclipseLink进行编织的信息,以及有关如何在未使用时进行设置的链接。
这在JPA兼容的应用服务器中是自动的,因此通常在演示和教程中被忽略。

您还可以使用连接或批量读取来加速相关的参考查找,但对于编织和惰性关系可能不是必需的。 http://wiki.eclipse.org/EclipseLink/Examples/JPA/QueryOptimization