1

Based on object-oriented approach, I write the following entities:

@Entity
public class Customer {

  @Id
  private String id;

  @OneToMany
  private List<Order> orders;

  public BigDecimal getTotal() {
     // iterate over orders and sum the total
     BigDecimal total = BigDecimal.ZERO;
     for (Order o: orders) {
        total = total.add(o.getTotal());
     }
     return total;
  }

  ... // getter & setter

}

@Entity
public class Order {

  @Id
  private String id;

  private BigDecimal total;

  ...

}

I realized that when calling getTotal() method for a Customer, Hibernate will issue a SELECT * FROM Order query to retrieve all Orders. The number of Order will surely increase as years passed. I believe a SELECT SUM(o.total) FROM Order o will give a better performance, CMIIMW. I just don't know where should I put the query? Rules of object oriented design suggest that getTotal() should be part of Customer, but the framework I'm using (Spring Transaction) doesn't allow transaction in domain objects.

David Bower
  • 121
  • 2
  • 10
  • 1
    Ever though on a calculated field as shown in answers to [this question](http://stackoverflow.com/questions/2986318/calculated-property-with-jpa-hibernate)? – Uwe Plonus Jun 27 '13 at 07:48
  • [Here's](http://www.jroller.com/eyallupu/entry/hibernate_derived_properties_performance_and) your answer. – Boris the Spider Jun 27 '13 at 07:51
  • Thank you for the answer. I never heard about @Formula before, but it will solve my problem. – David Bower Jun 27 '13 at 08:03

1 Answers1

0
In the first case, select * from orders.

You are just getting the list of orders and you need to calculate the sum in Server side code with iterating over the orders.

In the second case, select sum(o.total) from orders where order.customer_ id = 1234;

Database is doing the calculation for you. In terms of performance also, this is better.

Why the database needs to delegate to some upper layer, when It can do it.

So I suggest you with the second case only.

As per OO, It might suggest to encapsulate both properties and related methods.

But its a Domain Class, which gets directly mapped to fields in Database.

To separate Data Access Logic, We can have a separate layer i.e DAO and put the desired logic in it.

omkar sirra
  • 696
  • 10
  • 28