I am using springboot(spring-boot-starter-parent 2.3.0 version) along with Jpa. I have User class which is parent and UserEmails as a child entity.
User Entity
@Entity
@Table(name = "user")
public class User extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotEmpty(message = "Name cannot be empty")
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "user",fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private List<UserEmails> userEmails = new ArrayList<UserEmails>();
//setters and getters
public void setUserEmails(List<UserEmails> userEmails) {
this.userEmails= userEmails;
this.userEmails.forEach(userEmail->{
userEmail.setUser(this);
});
}
}
UserRoles Entity
@Entity
@Table(name = "user_emails")
public class UserEmails extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="email")
private String email;
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id" , referencedColumnName = "id", nullable=true)
private User user;
//getters and setters
}
The issue is that, even though i have used fetch type as lazy at the both the sides of the relationship, still when i call getUserById or getAllUsers, jpa loads user emails as well.
UserServiceImpl
@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
UserDAO userDAO;
@Override
public User getUserById(int id) {
logger.info("Executing getUserById() in user service");
User user = null;
try {
user = userDAO.findById(id);
} catch (DataAccessException e) {
String message = "Some message"
throw new Exception(message, e);
}
if (user == null) {
String message = "Some message"
throw new ResourceNotFoundException(message);
}
return user;
}
}
UserDAO
@Repository
public interface UserDAO extends JpaRepository<User, Long>{
public User findById(int id);
}