title: Hibernate: findById vs getbyId
body: <p>having this classes:</p>
  <p><em>User.java</em>:</p>
  <pre><code>@Entity
  @Setter
  @Getter
  @NoArgsConstructor
  public class User {
      @Id
      private int id;
      private String username;
      @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
      private Address address;
  
      public User(String username) {
          this.username = username;
      }
  }
  </code></pre>
  <p><em>Address.java</em>:</p>
  <pre><code>@Entity
  @Data
  public class Address {
      @Id
      private int id;
      private String country;
      @OneToOne
      private User user;
  }
  </code></pre>
  <p><em>UserRepository.java</em>:</p>
  <pre><code>@Repository
  public interface UserRepository extends JpaRepository&lt;User, Integer&gt; {
  }
  </code></pre>
  <p><em>DemoApplcation.java</em>:</p>
  <pre><code>@Bean
      public CommandLineRunner loadData(UserRepository userRepo){
          return new CommandLineRunner() {
              @Override
              public void run(String... args) throws Exception {
                  User u = new User(&quot;motherfucker&quot;);
                  Address a = new Address();
                  a.setCountry(&quot;CZ&quot;);
                  u.setAddress(a);
                  a.setUser(u);
                  userRepo.save(u);
  
                  //User newUser = userRepo.getById(0);
                  User newUser = userRepo.findById(0).orElse(null);
                  System.out.println(newUser.getUsername());
              }
          };
      }
  </code></pre>
  <p>Now the <code>findById(int: id)</code> works without problem (defined in <code>CrudRepository</code> from which extends <code>JpaRepository</code>). However the <code>getById(int :id)</code> (defined in <code>JpaRepository</code>) gives <code>LazyInitializationException</code> even with <code>fetch = Fetch.EAGER</code> attribute specified in mapping. In <a href="https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html#getById-ID-" rel="noreferrer">documentation</a> it says</p>
  <blockquote>
  <p>Returns a reference to the entity with the given identifier. Depending
  on how the JPA persistence provider is implemented this is very likely
  to always return an instance and throw an EntityNotFoundException on
  first access. Some of them will reject invalid identifiers
  immediately.</p>
  </blockquote>
  <ol>
  <li>I didn't get <code>EntityNotFoundException</code> but <code>LazyInitializationException</code></li>
  <li>Why is there a method which declares in its documentation that it throws exception without any reason? -&gt; <strong>always</strong> return an instance and <em>throw</em> an EntityNotFoundException</li>
  </ol>
  <p>from this description it seems for me this method be useless if it always throws exception. Why does this method exists?</p>
  <p>What is the right way (method) for fetching data in hibernate?</p>