Skip to content
Advertisement

Spring Data JDBC – Many-to-One Relationship

I can’t seem to find any reference online with regards to using a Many-To-One mapping in Spring JDBC. I just saw in the documentation that is not supported but I’m not sure if this is the case.

My example is that I want to map my AppUser to a particular Department.

For reference, AppUser joins to Department table using DEPARTMENT_ID

JavaScript

However, it seems that it won’t map properly.

JavaScript

The created query looks like this. I was looking for something more of the opposite in which M_APPUSER.department_ID = Department.id

JavaScript

Thanks

Advertisement

Answer

I just saw in the documentation that is not supported but I’m not sure if this is the case.

I can confirm it is not supported. Many-To-One relationships cross the boundaries of aggregates. References across aggregates must be modelled as ids of the referenced aggregate.

If you don’t do this Spring Data JDBC will consider the reference a One-To-One relationship and part of the same aggregate which will have effects you don’t want for a Many-To-One relationship, like the referenced entity getting deleted when the referenced entity gets deleted. Which would be correct for a One-To-One relationship within the same aggregate.

This is explained in more detail in https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement