uksz
uksz

Reputation: 18719

Load only IDs of ManyToOne relationship

I am having performance issues using hibernate. I have the following:

@Data
@Entity
@Table(name="\"Order_product\"")
public class OrderProduct {
    @Id
    @SequenceGenerator(name="Order_product_id_seq",
            sequenceName="Order_product_id_seq",
            allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator="Order_product_id_seq")
    private long id;
    @ManyToOne
    @NotNull
    private Product product;
    @ManyToOne
    @NotNull
    private ProductPrice price;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @NotNull
    private Order order;
}

Now, whenever I am trying to execute:

List<OrderProduct> findByOrderId(@Param(value = "order") Long orderId);

Hibernate will load whole Order for each OrderProduct. How can I disable this, so that only ID of the Order will load?

Upvotes: 7

Views: 6074

Answers (1)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23562

You are already on a good track as the association is lazy, so Hibernate will make a proxy of Order in the order field.

However, the proxy instance is initialized as soon as you call any of its methods. Take a look at this question about how to disable proxy initialization when you need only id (foreign key pointing to the associated entity in your case). Of course, make sure not to invoke other methods on the proxy.

Alternatively, you could map the foreign key column explicitly and use it instead of accessing the associated entity (it has to be neither insertable nor updatable because the column is already mapped in the association):

@Column(name = "order_id", insertable = false, updatable = false)
private long orderId;

Upvotes: 8

Related Questions