I am trying to populate my database, and during this, I create a associations between employees and teams. I'm trying to access the team members on a team via a hibernate OneToMany reference and doing lazy loading. This works great in my app, except when I call it right after the entities are created.
I'm fairly certain this is a hibernate transaction or caching issue, as all of the rows exist in the database, but I'm struggling to understand what the issue is. I have tried converting all of the saves in the populateTeamsAndEmployees
function to saveAndFlush, but that did not help.
How can I make team.getTeamMembers() work every time it is called?
Note: This only happens when I call the seedData()
function via RequestMapping
, but it doesn't happen when I call seedData()
with a @Scheduled
annotation
Function with Problem
void seedData() {
populateTeamsAndEmployees()
otherBusinessLogic()
}
public void otherBusinessLogic() {
List<Team> teams = teamRepository.findAll();
teams.foreach(team -> {
/*
works great every time, returns all team members
*/
List<Employee> teamMembers = employeeRepository.findEmployeeByTeamId(team.getId());
/*
this returns null when ran immediately after populateTeamsAndEmployees(),
but returns the same as the line above all other times
*/
List<Employee> thisDoesntWork = team.getTeamMembers();
});
}
public void populateTeamsAndEmployees() {
List<EmployeeFromOtherSystem> employeesToConvert = otherSystemRepo.findAll();
employeesToConvert.foreach(otherSysEmployee -> {
employeeRepository.save(otherSysEmployee.toEmployee());
});
}
Entities:
class Team {
@OneToMany(mappedBy = "team", fetch = FetchType.LAZY)
private List<Employee> teamMembers;
}
class Employee {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TEAM_ID")
private Team team;
}