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

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);
    }
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)