When should you use @OneToOne with @JoinTable in Spring Data JPA?
Last updated on
Share your thoughts
Join tables are good when you want to avoid null values
@JoinTable gives you the best of both worlds because you can both allow null values AND not store them :)
If you are trying to use a @JoinTable with a @OneToOne relationship then you should be questioning your end goal in the first place...
Think about it. A @OneToOne relationship is typically required right? Like one customer has one address. So don't you want the address to be required?
The following can be used to not allow null values with @OneToOne associations...
The problem with this is that your application will throw exceptions if you don't set the associated entity.
The easy solution is to allow nulls aka remove the optional argument (the default is true)
The problem with this is that now you are storing null values in your database. This isn't good because it's wasted space basically....
The @JoinTable is the best of both worlds. You can store associations in a join table and also allow nulls. If associations are null then it just doesn't get stored in the join table...