I have a JPA application, with an entity diagram, that shows the relations between orders and customers.
I have an ItemType entity class as such:
@Entity
public class ItemType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
private int price;
List<OrderLine> orderlines;
the class contains a list of OrderLines because it has a one to many relationships to the orderline entity.
Here is my OrderLine entity. It contains a single instance of the ItemType class, because of the relationship.
@Entity
public class OrderLine implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int quantity;
private Order order;
private ItemType itemtype;
I have a facade class, where i have made different methods, to calculate and select elements from my database, but i want to make a calculatePrice method, which multiplies the quantity from the orderline with the price from ItemType.
I know that the functions need to take both an ItemType instance and an OrderLine instance like such:
public int getTotalPrice(ItemType itemtype, OrderLine orderline){
}
but I'm not sure if I should use NamedQueries within the entity classes, to get the data from the database, or I should use something like a value annotation, that can make a calculation.
Both options are valid and have pluses and minuses.
If you define it as Query, what you will gain is less java code. The query will be bound to your entity , in a way it would be less verbose.
On the cons side you will not be able to take advantage of the Level 1 cache that hibernate session presents. The only way to cache the results would be through second level query cache if you configure it and still this type of caching is not very good.
If you decide to go with java you will take full advantage of your Hibernate Session and its functionality. You will have very good control over what queries how often how much are executed. You will be able to debug your Java code. You will be able to unit test it.
Summary of your options: