What's the advantage of load() vs get() in Hibernate?

前端 未结 10 2738
感情败类
感情败类 2020-12-02 04:58

Can anyone tell me what\'s the advantage of load() vs get() in Hibernate?

10条回答
  •  半阙折子戏
    2020-12-02 05:27

    Explanation of semantics of these methods doesn't explain the practical difference between them. Practical rule is the following:

    • Use get() when you want to load an object

    • Use load() when you need to obtain a reference to the object without issuing extra SQL queries, for example, to create a relationship with another object:

      public void savePost(long authorId, String text) {
          Post p = new Post();
          p.setText(text);
      
          // No SELECT query here. 
          // Existence of Author is ensured by foreign key constraint on Post.
          p.setAuthor(s.load(Author.class, authorId));
      
          s.save(p);
      }
      

提交回复
热议问题