I’ve been programming api/font end apps for a while now with dotnet webapi & entity framework for orm then springboot with jpa, because of this my native sql query skill’s are medicore so i recently ditched using any orm’s in my side projects and retorted to calling native sql function’s/view’s/crud qurie’s, after playing with these for a while i have so many questions,after using sql function’s my api business layer barely has any logic, most of the codes only do data validation and pass the parameter’s to the sql function via jdbc or jpa native query,
- is sql functions doing most of the business logic normal and is it a good practice?
- how do you handle error/success message return’s to the client, right now iam returning
json directly from pgsql but i feel like it is not the best practice. - what is faster? orm or using orm to call native sql scripts?
2
Answers
Using SQL directly for CRUD operations is perfectly fine, I think.
ORM handles things like tracking which fields to update, in which order to do queries, mapping relations between objects, etc. But you can write maintainable and performant applications without it.
In theory, if you write your own SQL, it can be at least as fast or even faster than what an ORM does, but you need to remember to optimize things that an ORM would do out-of-the-box. Things like session caching, 2nd level caching, reusing prepared statements, batch processing, eager/lazy loading, etc.
There are some things that are much harder to implement and maintain in SQL, however. If your application is just CRUD on entities one at a time, then there is not much ‘Business Logic’ involved, and your SQL functions can perfectly handle this with simple INSERT/UPDATE/UPSERT/DELETE commands, and for read logic, I’d even recommend creating your own SELECT statements if you’re good with it.
What do I consider ‘Business Logic’:
For use cases like this, you should first write the CRUD operations, either with SQL or ORM, and then write the actual use case in a bit of code that is independent of the CRUD layer. That way it’s easier later if you need to change anything: you know where to look for what functionality.
A question like this, gets answers based on opinions. Here’s mine:
We have almost all logic in the database, in SQL and PL/pgSQL, for raw speed where every millisecond counts. We just can’t afford any network overhead. Is it the best? I don’t know. Can we maintain it? Yes. Does it work? Yes. Is the customer happy? Yes, and that’s the only thing that counts.