Hi All,
I’m using Hibernate a lot in my new project and combine it with QueryDSL which I started implementing instead of native SQL queries which became cumbersome and hard to maintain.
The biggest knowledge gap I have is how to properly map relations in my project, ManyToMany in particular.
I’ve read the article Vlad posted (thank you for your hard work it is a lifesaver), about proper handling this relational type.
However, I have a helper class which I use in my integration test which constructs entities at the repository level (so I can test all layers of my code) and when I use the above add method I get an NPE exception which indicates that the initialization of my classes property (one side of the relation) wasn’t initialized. Here is the code block:
private Entity create(Long accountId, String name, Set<AnotherEntity> others) {
var entity = Entity.builder()
.accountId(accountId)
.name(name)
.build();
repository.save(entity);
other.forEach(entity::addOther); -> NPE
return entity;
}
Here is how the relations are organized:
/* Inside Entity class */
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "entity_other",
joinColumns = @JoinColumn(name = "entity_id"),
inverseJoinColumns = @JoinColumn(name = "other_id")
)
private Set<OtherEntity> others = new HashSet<>();
public void addOther(OtherEntity other) {
others.add(other); // NPE like others wasn't initialized to new HashSet<>()
other.getEntities().add(this);
}
/* Inside Other class */
@ToString.Exclude
@ManyToMany(mappedBy = "others")
private Set<Entity> entities = new HashSet<>();
I’ve just changed names for the purpose of hiding the business logic.
I’m wondering do we need to implement manipulations with the repository in a thin layer that we can call the Service layer or OtherCrud.class which should provide us access to the repository and escape usage of the repository outside of the above-mentioned service class in general.
Also if there are some useful things to note about the relationship please let me know.
Thank you very much in advance.