Hi there!
I am trying to use @OneToMany annotation, but do see some weird results, provided by EntityManager.
I use Spring Boot and code is actually run in test scope.
Here is my example:
@Data
@Entity
@Table(name = "referral_program")
public class Program {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String title;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "referral_program_id")
List<Bonus> bonuses = new ArrayList<>();
}
@Data
@Entity
@Table(name = "referral_bonus")
public class Bonus {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column(name = "referral_program_id")
Long programId;
}
@Repository
public interface ReferralProgramRepository extends JpaRepository<Program, Long>, PagingAndSortingRepository<Program, Long> {}
@Service
@AllArgsConstructor
public class ReferralService {
private final EntityManager entityManager;
public List<Bonus> getAllBonuses() {
return entityManager.createQuery("from Bonus ", Bonus.class).getResultList();
}
}
So, here is a test:
@SpringBootTest
@Transactional
public class BonusTest extends TestContainersBase {
@Autowired
ReferralProgramRepository referralProgramRepository;
@Test
@Rollback
@DisplayName("Bonuses have Program.Id")
void testIt() throws Exception {
var bonus_reg_referral = new Bonus();
var bonus_reg_referee = new Bonus();
var prg = new Program();
prg.setTitle("prg-1");
prg.setBonuses(
List.of(
bonus_reg_referral,
bonus_reg_referee
));
referralProgramRepository.save(prg);
assertEquals(2, entityManager.createQuery("from Bonus where programId = :id", Bonus.class)
.setParameter("id", prg.getId())
.getResultList()
.size());
assertEquals(2, referralService.getAllBonuses().stream().filter(b -> b.getProgramId() != null).toList().size());
}
So, the latest assertEquals fails.
Moreover. I do not understand why the previous assertEquals works, because when I run
entityManager.createQuery("from Bonus where programId = :id", Bonus.class)
.setParameter("id", prg.getId())
.getResultList()
it shows me the list, but all programId
are null.
Here are logs, shown by Hibernate;
Hibernate: insert into referral_program (title) values (?)
Hibernate: insert into referral_bonus (referral_program_id) values (?)
Hibernate: insert into referral_bonus (referral_program_id) values (?)
Hibernate: update referral_bonus set referral_program_id=? where id=?
Hibernate: update referral_bonus set referral_program_id=? where id=?
Please help understand what I did wrong.
Many thanks in advance!