Sam Levin
Sam Levin

Reputation: 3416

JPA IdClass confusion - is this idea practical?

If you have a user entity, you could store his/her address in two ways. You could store all of the fields in the user object directly -or- you could create an address object which is persisted in a separate table and joined to the user (or cascaded, or whatever) and put into an address object inside the user entity.

What is the advantage of doing the latter? If you can fit more stuff into a single table, doesn't that make the most sense? I would presume the latter would end up incurring more resource usage. I get that it can be more practical for other things, but the example specifically mentions a situation where you could do either.

Is a user something you would generally use an IdClass for, if you did something similar to what I've described above?

For an IdClass, must EVERY field simply be a key to another entity, or can you have concrete or transient fields there in addition? Is usage of @IdClass simply saying to expect multiple Id annotations, and the rest is up to you?

Thanks!

Upvotes: 0

Views: 201

Answers (1)

Niroshan Abayakoon
Niroshan Abayakoon

Reputation: 921

You User to address relationship should be many to one. Because one user may have two addresses. If you going to put address object inside the user object you can have only one address for a user. Having the address fields in user object is also having that issue. So both your suggestions are not the best practices.

No need to use a IdClass for User entity you can simply use database native id genoration by annotations. `@Id @GeneratedValue(strategy=GenerationType.IDENTITY).

Upvotes: 1

Related Questions