1

Let's suppose we have the hibernate entities User and Post. A user can have many posts.

Suppose we are never going to get the user with their posts; we always only are going to need to get the list of posts that belong to a user, but without the user info.

In this case, it's necessary to have in the entity Post an attribute with type User with the annotation @ManyToOne?

Or is it valid to have just an attribute userid type Integer? This way the jpql query would be like:

select p from Post p where p.userid = :userid
Bohemian
  • 412,405
  • 93
  • 575
  • 722
Juliancho9191
  • 121
  • 12

2 Answers2

1

You can have the best of both worlds with LAZY fetch:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="USER_ID")
private User user;

The user data is only fetched if you access the user field.

You can still fetch all posts as per your query without hitting the user table.

You can take the same approach with the User class:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Post> posts;

with similar effect. Or just leave the posts field out altogether.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • This is a great addition but more upfront work. On top of that I would always want future developers to think more when they want to really make that join, removing the `fetch = FetchType.LAZY` attribute is too quick :) . And if you dont have use cases that you need User and Posts together, this relation will not be referenced in other places of your code anyway. – mcvkr Aug 29 '21 at 00:09
  • @mcvkr “performance” is the last consideration: maintainability and readability trump performance. Once functionality is working, you can fine tune aspects to make it faster. Fetching 1 row once for a bunch of posts is not going to make a difference you could feel. – Bohemian Aug 29 '21 at 00:26
  • That is another great point. If the User object has other relations to load, it will make a difference though. Many times developers add relations without knowing the default fetch type: https://stackoverflow.com/a/26601720/2815227 and the service degradation could be a difficult production issue to fix. – mcvkr Aug 29 '21 at 00:32
-1

Or is it valid to have just an attribute userid type Integer ?

This is totally valid and will be more performant to start with. You can add to many-to-one relationship later if need be. I personally don't add relationships until I really need them.

On top of this, if you (will) keep user and posts separate you don't need to put the posts in an SQL database, you can have them on a document oriented database such as MongoDb and have a much better throughput. The disadvantage of this second advice is though; you will have two different database types in your stack to maintain.

mcvkr
  • 3,209
  • 6
  • 38
  • 63