Should persistent classes initialize instance variable collections

后端 未结 4 1715
慢半拍i
慢半拍i 2021-01-04 08:43

In my Hibernate classes should instance collections be initialized

public class Basket {
    private List items = new ArrayList();

    ...getters and setter         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 09:33

    I cannot back it up with any sort of professional documentation, but here is my opinion on that matter. I think you have two possible roads to follow.

    DTOs only

    The first one relies on Model beans to be plain DTOs, used only for data persistence, performing no logic. Here you can leave your POJO fields uninitialized, since that will be done automatically by Hibernate before you'll retrieve persistent object via Session. I'm sure you already know, that Hibernate will silently wrap all collections into it's own wrappers, which is needed by internal persistence mechanism.

    Proper model classes

    The second approach takes POJOs a little bit further. In this scenario you can perform some logic within the getters and setters methods. This is not that uncommon scenario, after all it's perfectly acceptable by MVC and very often one would find himself in need of adding some code to them. For instance - logging some information while calling setter method, example below:

    public void setItems(List items){
       LOGGER.info("Setting '{}' new items", items.size());
       this.items = items;
    }
    
    
    

    In that case, one could fell into trouble, since as far as I know the collection will not be initialized by Hibernate at this point. In that case explicit initialization would be better.

    Final remark: I'm not the expert on Hibernate, I also do not know if anything has changed in 4.x, but I know I endured this problem at some point.

    提交回复
    热议问题