Issue
I'm new to "normal" back-end development and I'm trying to implement comment system for my Spring Web application. The catch here is that if a comment gets downvoted then comment owner's "karma" must be decremented as well.
Now, I had some experience with web development in PHP with some self-made spaghetti-coded frameworks, where one could implement the said logic with something like that:
class Comment {
function getUser() { return db_find("users", User::class, $this->columns->owner); }
function downvote() {
$user = $this->getUser();
$user->columns->karma--;
db_persist("users", $user);
}
}
JPA beans are made differently so I couldn't reapply the above solution to it, although my initial idea was pretty similar. I believe it is possible to achieve something like that by passing Session to the downvote method this way:
class Comment {
// ...
@ManyToOne
@JoinColumn(name = "owner_id")
var owner: User? = null
fun downvote(session: Session) {
this.rating -= 1;
this.owner.karma -= 1;
session.save(this.owner)
session.save(this)
}
}
But it seems really wrong and unnatural to me. I've also had an idea to put this logic in controller, but that one seems like a bad practice too...
So, I kinda have an entity (comment) that should modify another entity (user) on modification (call to downvote) and I'm not sure how to implement all this in JPA-like way.
Solution
First of all, you should separate the logic (e.g., transaction operations) from the entity.
The entity should be (more or less) a pojo, you create another class for those business logic implementations.
A typical architecture would be:
- entities: pojos
- dao or repositories: each repository usually talks (read/write) to one entity class
- services (here you can modify as many entities as you need through required repositories)
Answered By - Kent
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)