Hibernate Inheritance Strategy and Why

后端 未结 3 1865
感情败类
感情败类 2020-12-18 13:53

I have 3 non-abstract persist-able classes. MyClubUser and HisClubUser classes inherit from User class. I use one table per subclass strategy i.e. @Inheritance(strateg

3条回答
  •  盖世英雄少女心
    2020-12-18 14:33

    Hibernate ALWAYS returns the actual type of persisted entity. If you've stored "MyClubUser" it will be returned as "MyClubUser", never as "User". The reason for this is quite clear - if Hibernate were to return "MyClubUser" as "User" and you were to persist it again you would lose all additional properties defined in "MyClubUser".

    In order to do that, Hibernate needs to know what that actual type is. For InheritanceType.JOINED strategy the only way to find that out is to check all the tables in your inheritance hierarchy (well, technically it's all tables at or below current level plus all tables above current level in current tree branch). So, if you have a hierarchy like:

               Root
              /   \
          Node1  Node2
          /   \
       Node11 Node12
    

    and you're trying to select from root, Hibernate will do an outer join on ALL tables. If you're selecting from Node1, Hibernate will do an inner join on Node1 and Root plus an outer join on Node11 and Node12. Node2 won't be touched because it's not a descendant of Node1.

    As far as outer join overhead goes - yes, there's definitely an overhead but that's the price you pay for joined strategy. You can use discriminators to avoid this but that comes with its own side effects. Whether that overhead is significant or not depends on the depth and spread of your hierarchy, your indexes and many other things. Listen to KLE's suggestion and profile it.

提交回复
热议问题