Performance difference between annotating fields or getter methods in Hibernate / JPA

前端 未结 3 1705
太阳男子
太阳男子 2020-12-16 04:09

I was curious if anyone had any hard numbers around the performance difference between annotating Entities using private fields instead of public getter methods. I\'ve hear

相关标签:
3条回答
  • 2020-12-16 04:48

    ok, I can't give numbers haha, but I would guess that accessing the fields through reflection wouldn't be a 'one time' thing. Each object has its own private members.

    I honestly don't know much about reflection but the getter/setters should be straight forward. In fact you can try setting one of the methods to private and I think it won't work because it can't find the method it needs.

    There are other issues like proxies that will affect getter methods though depending on how you load your entities.

    This is all I see in the documentation:

    The access attribute lets you control how Hibernate will access the property at runtime. By default, Hibernate will call the property get/set pair. If you specify access="field", Hibernate will bypass the get/set pair and access the field directly, using reflection. You may specify your own strategy for property access by naming a class that implements the interface org.hibernate.property.PropertyAccessor.

    My guess is that reflection in general is going to be a higher cost though, but sorry.. no numbers :(

    0 讨论(0)
  • 2020-12-16 05:05

    Loaded 5000 records into a simple 3 column table. Mapped two classes to that table, one using annotated private fields and another using annotated public getters. Ran 30 runs of Spring's HibernateTemplate.loadAll() followed by a HibernateTemplate.clear() to purge the Session cache. Results in ms below...

    methods total: 6510, average: 217

    fields total: 6586, average: 219

    I should probably take another stab at it after adding more properties to each class but right now the difference doesn't appear to be statistically significant.

    0 讨论(0)
  • 2020-12-16 05:09

    Generally use annotation in above of getter methods, Because when class is loaded in JVM ath that hibernate model or entity class is also loaded then if you use annotation above of field or peroperty then it will execute only once at time of each request. whereas if you placing above getter then in reflaction or any other layer when it will caled this class then getter method called then this become very useful

    0 讨论(0)
提交回复
热议问题