javahibernatejpa

Which approach is more efficient with hibernate


Let's consider a class Transaction

 @Entity
    public class Transaction {
    
    @ManyToOne(fetch = FetchType.EAGER)
    private Business business;
    
        @Column(name = "business_code")
        private String businessCode;
    
    
    }

which method is more efficient to fetch transactions by business using byBusinessCode which is a column in the table Transaction or using byBusiness so the whole object Business which is a dependency in the class Transaction ?


Solution

  • There is no conceptual difference between a "column in the table" and a "whole object": The "whole object" is a column in the table, too!

    If you look at the actual database schema, we have something like

    +-------------+       +-------------+
    |Transaction  |       | Business    |
    +-------------+       +-------------+
    |business_id  |------>| business_id |
    |business_code|       | ...         |
    +-------------+       +-------------+
    

    if you query by business entity, hibernate will translate this to the SQL query

    select ... from Transaction where business_id = ?
    

    and if you query by code, hibernate will translate it to

    select ... from Transaction where business_code = ?
    

    As you can see, the SQL is structurally identical. The performance will therefore depend on the usual things, most notably whether there is a suitable index on this field (which hibernate creates automatically for primary and foreign keys, but may need to be manually created for other columns), and to a lesser extent on the datatypes of the fields involved.

    (the answer would be different if the relationship were a @OneToOne(mappedBy = ...) the other table. Then, the database schema would look like

    +---------------+       +----------------+
    |Transaction    |       | Business       |
    +---------------+       +----------------+
    |transaction_id |<------| transaction_id |
    |business_code  |       | business_id    |
    +---------------+       +----------------+
    

    and querying a transaction by business would translate to

    select ... 
    from Business 
    left join Transaction on Business.transaction_id = Transaction.transaction_id 
    where business_id = ?
    

    and that join would create extra work for the database that might have performance implications. But @ManyToOne can not use mappedBy, so this can not happen in your case.)

    BTW, you can easily check what your queries are being translated into by turning on Hibernate's SQL logging. If you are new to hibernate, I recommend doing so to better understand what it does.