JPA一对一映射FetchType.LAZY不起作用

时间:2014-09-25 07:01:39

标签: mysql jpa

我有两个实体,如下面的

@Entity
@Table(name = "ticket")
public class Ticket {

    @OneToOne(fetch=FetchType.LAZY, targetEntity = com.vahana.entity.TicketBookingAdditionalInfo.class, mappedBy = "ticket", cascade = CascadeType.MERGE)
    private TicketBookingAdditionalInfo ticketBookingAdditionalInfo;

}

@Entity
@Table(name = "ticket_booking_additional_info")
public class TicketBookingAdditionalInfo {

    /** The ticket. */
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinColumn(name = "ticket_id", columnDefinition = "BIGINT UNSIGNED")
    private Ticket ticket;

}

我的票证表包含40,000多条记录,但是订票额外信息没有任何数据。只有在我要添加其他信息时,此表才会包含数据。

在选择票证表时,它会加入ticket_booking_additional_info表,并且该查询需要更多时间。

我在@OneToOne中添加了fetch = FetchType.LAZY,但仍需要很长时间才能响应。这是我的数据库中最耗时的查询。如何避免这个问题。请有人指导我。

使用mysql DB,

1 个答案:

答案 0 :(得分:1)

@Entity
@Table(name = "ticket")
public class Ticket {

    //Default is lazy
    @OneToMany(mappedBy = "ticket", cascade = CascadeType.MERGE)
    private List<TicketBookingAdditionalInfo> ticketBookingAdditionalInfo;

}

@Entity
@Table(name = "ticket_booking_additional_info")
public class TicketBookingAdditionalInfo {

    // The ticket. 
    //Default is eager
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinColumn(name = "ticket_id", columnDefinition = "BIGINT UNSIGNED")
    private Ticket ticket;

}

注意 如果您有ManyToOne,则反向关系是OneToMany,如果您有OneToOne,则反之为OneToOne。您应该看到this教程