having this classes:
User.java:
@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;
}
}
Address.java:
@Entity
@Data
public class Address {
@Id
private int id;
private String country;
@OneToOne
private User user;
}
UserRepository.java:
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
DemoApplcation.java:
@Bean
public CommandLineRunner loadData(UserRepository userRepo){
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
User u = new User("motherfucker");
Address a = new Address();
a.setCountry("CZ");
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());
}
};
}
Now the findById(int: id)
works without problem (defined in CrudRepository
from which extends JpaRepository
). However the getById(int :id)
(defined in JpaRepository
) gives LazyInitializationException
even with fetch = Fetch.EAGER
attribute specified in mapping. In documentation it says
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.
- I didn't get
EntityNotFoundException
butLazyInitializationException
- Why is there a method which declares in its documentation that it throws exception without any reason? -> always return an instance and throw an EntityNotFoundException
from this description it seems for me this method be useless if it always throws exception. Why does this method exists?
What is the right way (method) for fetching data in hibernate?